jquery ajax方法和其余api回顾

>> $ele.load(url, data, callback); //带data参数时为POST请求,不然为GET请求
  // $('#testload').load('data.html', {"name": "peter"}, function(r){console.log(r);}); //POST 所有html添加到容器中
  // $('#testload').load('data.html h1', {"name": "peter"}, function(r){console.log(r);});//POST 部分html添加到容器中
  $('#testload').load('data.html h1', function(r){console.log(r);});//GET 部分html添加到容器中

>> $.get(url,data, callback);
  $.get('test.php', {name:'kk', age:'a little old'}, function(r){ console.log('get:' + r); $('#testget').html(r); });

>> $.post(url, data, callback); //和$.get()同样,只是请求的方式不一样
  $.post('test2.php',{title:'tower', des:'it is very tall'}, function(r){ console.log('post:' + r); $('#testpost').html(r); });

>> $.getJSON(url, data, callback); //当url为非同源的,则会用jsonp的方式工做

 1.  $.getJSON('test.js',{name: 'windy', age: 18}, function(json){ //json为对象,通过JSON.parse()
    console.log(json); $('#testgetjson').html( JSON.stringify(json) ); 
  });

  //当url为非同源的,则会用JSONP的方式请求
  //$.getJSON(crossUrl, data, callback);
  JSONP的工做方式: 回调函数callback 复制给临时全局函数jquery164509.., 临时全局函数传递给php页面,
  php页面组装函数调用表达式,而后做为<script>的内容返回给script, 解析执行后,删除临时的<script>标签
 2.  $.getJSON('http://localhost:800/jsonp.php?callback=?', {name:'windy', age:20}, jsonpback);
  function jsonpback(data){ $('#testjsonp').html('jsonp data:' + JSON.stringify(data) );}
  
>> $.getScript(url, callback)
  $.getScript('sayhi.js', function(r){ //加载并执行脚本文件
    console.log('getScript:' +r, +' script has been loaded and executed.');
    sayhi('summer');
  });

>>------------------------ $.ajax(options) --------------------------- // $.ajax(options)  //底层实现, 以上$.get(), $.post(), $.getJSON(), $.getScript() 内部都是调用$.ajax()的

 options = {
  type: 'GET / POST / PUT /DELETE'; //请求的方式 默认为GET, 如 PUT 和 DELETE 也能够使用,但仅部分浏览器支持。
  url: 'handler.php', //请求的地址 默认为当前页
  async: true, //是否异步请求
  php

  //发送到服务器的数据
  data: {name:'sindy', age:18}, //自动被转换为url参数形式(name=sindy&age=18), 也能够直接为字符串 'name=sidy&age=18'
  //对ajax返回的原始数据进行预处理的函数
  contentType: 'application/x-www-form-urlencoded', //内容的编码类型 默认为 application/x-www-form-urlencoded
  processData: true, //(默认: true) 默认状况下,发送的数据将被转换为对象(技术上讲并不是字符串)
                    以配合默认内容类型 "application/x-www-form-urlencoded"。若是要发送 DOM 树信息或其它不但愿转换的信息,请设置为 false。
  dataType: "xml / html /script / json / jsonp/ text", //预期服务器返回的数据类型
  dataFilter: function(data, type){.. },// data: ajax返回的数据, type: 调用$.ajax(options)时,指定的options.dataType

  timeout: 5000, //设置请求超时时间(毫秒) 此设置将覆盖全局设置

  beforeSend: function(xhr){
    this; //指向options
  },
  complete: function(xhr, textStatus){//请求完成(不管成功或失败)时的回调函数
    this; //指向options
  },
  success: function(data, textStatus){
     //data 多是xmlDoc, jsonObj, html, text等..
    this; //指向options
  },
  error: function(xhr, textStatus, error){
     this; //指向options
  },css

  global: true, //是否触发全局的ajax事件 (ajaxStart, ajaxStop)
  cache: false, //不从浏览器缓存加载请求信息
  ifModified: true, //默认false, 是否仅在服务器数据改变时获取新数据, 使用Http包 last-modified头信息判断
  
  jsonpCallback:'mycallback', //在jsonp请求中,重写url参数里的callback部分的回调函数(http://example.com/test.php?name="cici"&callback=?), 变为callback=myCallback
  scriptCharset: 'utf-8', //只有当请求时dataType为"jsonp"或"script",而且type是"GET"才会用于强制修改charset。一般在本地和远程的内容编码不一样时使用。

  password: '123'; //用于响应Http访问认证请求的密码
  username: 'yourname' //用于响应Http访问认证请求的用户名
}html

jsonpCallback参数示例:jquery

var mycallback;
var url = 'http://localhost:8015/user.php';
$.ajax({
  url: url,
  method: 'get',
  data:null,
  dataType:'jsonp',
  jsonpCallback:'mycallback',
  success:function(data, textStatus,xhr){
   console.log(data, textStatus);
  }
});ajax

>>-------------------- ajax事件 -----------------json

1. $ele.ajaxComplete(callback);跨域

$('#msg').ajaxComplete(function(event, xhr, ajaxOptions){数组

  $(this).append('<li>请求完成</li>');promise

}浏览器

2. $ele.ajaxSuccess(callback);

3. $ele.ajaxError(callback);

4. $ele.ajaxSend(callback);

$('#msg').ajaxSend(function(event, xhr, ajaxOptions){

  $(this).append('<li>开始请求: ' + ajaxOptions.url + '</li>');

}

5. $ele.ajaxStart(callback);

$('#loading').ajaxStart(function(){ $(this).show(); }

6. $ele.ajaxStop(callback);

$('#loading').ajaxStop(function(){ $(this).hide(); }

 

>>---------------- $.ajaxSetup(options) -------------

> $.ajaxSetup(options); //全局设置,设置ajaxOptions的默认值

$.ajaxSetup({

  url:'handler.php',

  type:'POST',

  global:false

});

$.ajax({data:mydata}); 

> $form.serialize(); //把表单内的控件的name/value属性序列化为 url参数形式

$('form').serialize();

> $('form').serializeArray(); //把表单内控件的name/value属性序列化为对象数组,如[{name1:value1}, {name2:value2}]

 

 其余API

$.fn.map(function(index, ele))
$.fn.each(function(index, ele)) //迭代函数 return false 终止遍历
$.map(arr, function(ele, i))
// 隐式迭代

$(window).resize() -> $(window).trigger('resize')
$('body').click({hi:'hello'}, function(e){ console.log(e.data, 'clicked..');});

$.holdReady(true);
$.getScript('myplugin.js', function(){ $.holdReady(false); });

// load事件,url关联的元素: img, script, link, frames, iframes, window
$('form').bind('submit', false) => $('form').bind('submit', function(){ return false; }); //取消默认事件 和 事件冒泡
event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation();
$('a.disabled').on('click', false); //取消点击a的默认行为和事件冒泡

// trigger(), triggerHandler()触发事件时,传递数据
$('body').bind('myevent', function(evt, extraParams){ console.log(extraParams); });
$('body').trigger('myevent', 'hello');
$('body').on('myevent', function(evt, var1, var2){ console.log(var1, var2); });
$('body').trigger('myevent', ['hi', 'idle']);

$ele.delegate(selector, eventType, [eventData], handler);
$ele.delegate(selector, events);

// 自定义事件,事件命名空间, 解除绑定
$('div.test').off('click', '**');//移除全部代理事件
$('form').on('click.validator', 'button', validate);
$('form').on('keypress.validator', 'input', validate);
$('form').off('.validator');

event.originalEvent
event.target //触发事件的最深层元素
event.relatedTarget //mouseover mouseout
event.result //上一个事件处理函数的返回值
$('body').on('click', function(ev){ return 'good'; });
$('body').on('click', function(ev){ console.log(ev.result); });
event.which //按键对应的keyCode

// 避免在大文档中,过多的在document/body上代理事件 由于冒泡的路径比较长

 

// 建立事件
ev = $.Event('submit');
$form.trigger(ev);
ev.isDefaultPrevented();

event.target, event.currentTarget, this , (event.currentTarget==this)
// event.nameSpace
$('body').on('test.ns', function(ev){ console.log(ev.nameSpace);});
$('body').trigger('test.ns');

//动画
$ele.hide([duration],[easing],[complete] ); //slow normal fast 300, 500
$ele.hide(options);
options = {
duration: 'normal',
easing: 'linear', //默认支持 swing or linear
queue: true, //是否将动画放入队列中
specialEasing: {},
step: function(){}, //每一个动画属性的每次变化
progress: function(){}, //每一步动画完成后执行
complete: function(){},
done: function(){},
fail: function(){},
always: function(){}
}

$.fx.off = true; //关闭动画效果 直接设置为最终值
$ele.hide('normal'); //无动画效果了

$ele.animate(properties, duration, easing, complete);
//数值型属性 properties: width height margin padding left top scrollLeft scrollTop border-width font-size opacity
//相对值 +=10 -=4
$ele.animate({left: '+=200'}, 400).queue(function(){//效果加入队列
$(this).toggleClass('red');
$(this).dequeue();//取出队列下一个效果并执行
});
$.dequeue(ele,[queueName]); //队列名queueName默认为 fx
$ele.finish([queueName]);//结束正在进行的动画,清除队列,全部动画的css属性设置为最终值
$ele.stop(true, true); //相似finish(), 结束当前动画,当前动画的css属性设置为最终值,清除队列
$ele.stop(isClearQueue, isToTargetVal);
$.fx.interval; // 13 多少毫秒渲染1帧
$ele.queue([queueName]); //返回已执行的函数队列数
$ele.queue([queueName], newqueue);
$ele.queue([queueName], callback);//将函数加入到动画队列中,callback中须要执行$ele.dequeue()来让后续动画继续
$ele.queue(function(next){
//do sth..
next();//同 $ele.dequeue();
});
$.queue(ele,[queueName]);
$.queue(ele,[queueName],callback);
$ele.stop(clearqueue, jumpToEnd);
$ele.fadeIn(duration,[easing],[complete]);
$ele.fadeIn(options);
$ele.fadeOut(..);
$ele.fadeTo(duration, opacity, [easing], [complete]);
$ele.fadeToggle(duration, [easing], [complete]);
$ele.slideDown(...);
$ele.slideUp(...);
$ele.slideToggle(..);

$ele.load(url, data, callback);// dataType:'html'
$.get(url, data, callback, dataType);
$.post(url, data, callback, dataType);
$.getJSON(url, data, callback); //get post or jsonp , set dataType:'json'
$.getScript(url, callback); //加载并执行脚本文件, 添加 <script>标签 并在onload时执行回调

$.ajaxSetup(options);
$ele.ajaxSuccess(function(event, xhr, settings){ .. });
$ele.ajaxError();
$ele.ajaxComplete();
$ele.ajaxStart();
$ele.ajaxStop();
$ele.ajaxSend();

$.param(obj); //对象 对象数组 或jq对象(包含input元素的)
myobj = { a:{one:1, two:2, three:3}, b:[1,2,3]};
decodeURIComponent( $.param(myobj) );
obj = {width:100, height:400};
$.param(obj);
objArr = [{name:'foo', value:'fooval'}, {name:'bar', value:'barVal'}];
$.param(objArr);

$form.serialize();//表单序列化 name1=val1&name2=val2
$('input, textarea, select').serialize();//对包含表单元素的jq对象序列化
$form.serializeArray();//表单序列化为对象数组 [{name:.., value:..}, {name:.., value:...}]
$('input, textarea, select').serializeArray();//包含表单元素的jq对象序列化


$.ajax(url, [settings]);//返回jqxhr对象,jqxhr实现了 Promise 接口
$.ajax([settings]);
settings = {
accepts: {}, //请求头的content-type
async: true, //是否异步 注意跨域和jsop不支持异步
beforeSend: function(xhr, settings){}, //请求发送前的回调,若返回false将取消请求
cache: false, //是否缓存请求结果 script和jsonp默认不缓存
complete: function(){},
contents:{}, //根据给定的内容类型,解析结果
contentType: 'application/x-www-form-urlencoded; charset=utf8',
context: obj, //设置相关回调函数的上下文, 回调中this默认指向settings ~~颇有用的说
converters: {
"* text": window.String,
"text html": true,
"text json": jQuery.parseJSON,
"text xml": jQuery.parseXML
},
crossDomain: false, //若要在同域中强制跨域调用 设为true
data:{}, //object, string, array
dataFilter: function(data, type){}, //过滤返回的数据
dataType: 'json', //json, jsonp, script, text, html, xml, 
error: function(xhr, status, err){},
global: false, //是否触发全局的ajax事件
headers:{}, //额外设置的请求头数据
ifModified: false, //是否检查http头信息if-modify以决定是否成功
isLocal: false,
jsonp:'myjsonp', // myjsonp=? 而不是默认的callback=?
jsonpCallback: 'okcallback', //全局的函数名或匿名函数, ?myjsonp=okcallback
method: 'get', //get post.. jquery1.9添加 同旧参数 type
type:'get',
mimeType:'',
username:'',
password:'',
processData: true, //默认data为对象,则会转换为url参数形式发送
scriptCharset: 'utf-8',
statusCode:{}, //状态码对应的回调 {404: 404callback, 200: 200callback},
success: function(data, status, xhr){},
timeout: 3000,
traditional: false, //是否用传统方式序列化数据
url:''


}

//jqXhr对象是对原生xhr对象的封装,可经过jqxhr.getResponseHeader()获取响应头信息
//jqxhr.setRequestHeader(name, value);
//jqxhr.getAllResponseHeaders();
//jqxhr.getResponseHeader();
//jqxhr.abort();
//jquery1.5开始 jqxhr对象实现 Promise 接口, jqxhr提供了和回调函数名一致的方法 jqxhr.success(), jqxhr.error(), jqxhr.complete()

jqxhr.done(function(data, status, xhr){ }); //替代过期的 jqxhr.success()
jqxhr.fail(function(xhr, status, err){ }); //替代过期的 jqxhr.error()
jqxhr.always(function(data/xhr, status, xhr/err){ });//替代 jaxhr.complete()
jqxhr.then(doneCallback, failCallback);


$.ajaxSetup(options);//设置默认值

$(selector, [context]);
$(domElement);
$(domEles);
$(obj);
$(jqObj);
$(html, owndoc);
$(html, attrs);

$.parseHTML();
$.parseJSON();
$.parseXML();

$.noConflict();


$.sub();//建立jquery副本,其属性和方法修改不影响原来jquery, (过期方法,用插件替代)

$.when(deferreds); //能够传入一个或多个延迟对象,或普通的对象(done回调会被当即执行)
$.when($.get(url1), $.get(url2)).then(function(data1, data2){ });//当传递多个延迟对象给when时,实际上会被看作一个新的延迟对象(包含2个延迟)
$.when($.ajax(settings)).then(function(data, status, xhr){ });
$.when({'name':'idle', 'age': 22}).then(function(data){ console.log(data);});//当即resolve,执行doneCallback
$.when().then(function(){ console.log('fire at once');});

var df1 = $.Deferred();
var df2 = $.Deferred();

$.when(df1, df2).then(function(v1, v2){
console.log(v1, v2);
});

df1.resolve('hello');
df2.resolve('boy');

// ------

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
console.log( v1 ); // v1 is undefined
console.log( v2 ); // v2 is "abc"
console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});

d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );//多个参数,则doneCallback的入参为数组

// --------
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
/* a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively */
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
if ( /Whip It/.test(jqXHR.responseText) ) {
alert("First page has 'Whip It' somewhere.");
}
});


// Deferred延迟对象 jq1.5引入
var deferred = $.Deferred();
deferred.always(callback1, callback2..); //resolve or reject都执行的回调
$.get('data.php').always(function(){ console.log('complete..');});

deferred.done(calblack1, callback2..); //resolve时执行的回调
$.get('data.php').done(function(){ console.log('success get data');});

deferred.fail(callback1, callback2..); //reject时执行的回调
$.get('data.php').done(function(){ console.log('success');}).fail(function(){ console.log('fail');});

 

var deferred = $.Deferred();
deferred.resolve('hello');
deferred.state();// resolved

var promise = deferred.promise(); //promise对象是受限的deferred对象,不能经过resolve, reject改变状态

deferred.notify(args); //触发 progressCallback的执行
deferred.then(doneCallback, failCallback, progressCallback);
deferred.progress(callback);

deferred.notifyWith(context, [args]); //可指定progressCallback的上下文对象 其余同df.notify(args)
var df = $.Deferred();
df.progress(function(a){ console.log(this.name, a); });
var p = {name: 'sisi'};
df.notifyWith(p, ['sing']);

deferred.pipe(doneCb, failCb, progressCb); //用 df.then() 代替
var df = $.Deferred();
var df2 = df.pipe(function(value){//pipe返回新的延迟对象, then也是返回新的延迟对象
return value * 2; //旧的延迟对象被resolve,新的延迟对象也会接着resolve, (这里返回数值或对象则当即resolve新的延迟对象, 若返回另1个延迟对象 如: return $.ajax(url); 则当该延迟对象resolve时,df2跟着resolve)
}).done(function(v){ console.log(v);}); //延迟对象管道方式一个接一个地resolve
df.resolve(5);


//链式调用ajax
var request = $.ajax(url, {dataType: 'json'});
var chained = request.pipe(function(data){
return $.ajax(url2, {data: {user: data.userId}});
});
chained.done(function(data){ });

deferred.progress(progressCallback1, progressCallback2);

deferred.promise([targetObj]); //返回promise对象
// example1:
function asyncEvent(){
var dfd = $.Deferred();
setTimeout(function(){
dfd.resolve('great');
}, Math.floor(400+ Math.random()*2000));

setTimeout(function(){
dfd.reject('bad');
}, Math.floor(400+ Math.random()*2000));

setTimeout(function working(){
if(dfd.state() === 'pending'){
dfd.notify('working...');
setTimeout(working, 500);
}
}, 1);

return dfd.promise();
}

$.when( asyncEvent() ).then(
function(arg){
console.log('well', arg);
},
function(arg){
console.log('fail', arg);
},
function(arg){
console.log('going', arg);
}
);

// example2:
var obj = { hello: function(name){ console.log('hello', name); } };
var dfd = $.Deferred();
dfd.promise(obj); //让obj实现promise接口
dfd.resolve('alice');
obj.done(function(name){ obj.hello(name); }).hello('sisi');

deferred.reject([args]);
deferred.rejectWith(context, [args]);
deferred.resolve(args);
deferred.resolveWith(context, [args]);

deferred.state(); //返回延迟对象当前的状态:pending resolved rejected
deferred.then(doneCb, failCb, progressCb); //参考 df.pipe()

$ele.promise([type], [targetObj]); // type: 'fx', targetObj: 需绑定promise方法的对象
$('div').each(function(i){
$(this).fadeIn().fadeOut(1000 * (i+1) );//一个接一个div渐隐
});
$('div').promise() //返回promise对象 会在动画结束后被resolve
.done(function(){ console.log('finished..')});

function effect(){
return $('div').fadeIn(800).delay(1200).fadeOut();
}
$.when( effect() ).done(function(){ console.log('finished..'); });

$.contains(container, contained);//检测一个元素是否在另外一个元素内 container需为domElement
$.each(collection, function(key, val){ });//迭代函数 可迭代对象和数组 , 返回false终止迭代
$.extend(target, [object1], [objectN]);
$.extend(deep, target, [object1], [objectN]);//深度拷贝
$.extend({}, src1, src2); //undefined值不会被复制
$.globalEval(code); //在全局上下文执行一些代码
function test(){
$.globalEval('var newvar = true; ');
}
test();

$.grep(array, function(ele, idx){ return true;}, invert); //相似[].filter, 返回过滤后的新数组
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$.grep(arr, function(n, i){ return n> 5; });
$.inArray(value, arr, fromIndex); //相似 [].indexOf();
$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] ); // -1 严格比较

$.isArray();
$.isEmptyObject(); //{}
$.isPlainObject();//{name:'sisi'}
$.isFunction();
$.isNumeric();
$.isWindow();
$.isXMLDoc(document); //false
$.makeArray();//类数组orjq对象转换为数组 ~~$.makeArray(arguments)
$.map(collection, function(ele, key){ });
$.merge(arr1, arr2);//合并数组元素 arr1会被扩展
$.merge([], arr2); //克隆数组
$.merge( [0,1,2], [2,3,4] ); //[0, 1, 2, 2, 3, 4]  ~~$.unique( $.merge(arr1, arr2) ) 合并数组并去重
$.noop;
$.now(); // (new Date).getTime()

$.parseHTML(data, [context], [keepScript]);
$.parseJSON(json);//注意传入的是严格的json
$.parseXML(data); //返回xmldoc

$.proxy(fn, context, [args]); //返回为fn绑定上下文后的新函数, 还可绑定部分参数。相似bind
$.proxy(objec, method); //固定对象方法的上下文为自身

$.support;//建议用外部库 modernizr, $.support包含不少特性检测的结果,如: $.support.ajax, $.support.boxModel
$.trim([str]);
$.type(param); //数据类型判断
$.type(''); $.type([]); $.type(/test/)
$.unique(arr); //数组或dom元素去重

$ele.get([index]);//返回dom元素 或 dom元素数组 ~~$ele.get() 类数组转换为真正的数组
$ele.index(); //表示范围为 兄弟节点
$ele.index(selector); //选择器参数 ,表示查找的范围
$ele.index(element); //dom元素或jq对象,表示被查找的元素,而$ele表示查找范围
$ele.toArray(); //同 $ele.get()
$ele.context;
$ele.selector;

$.Callbacks(); //事件处理能力 jq1.7+
$.Callbacks( 'unique stopOnFalse' ); //flags: once, menory,unique, stopOnFalse
var callbacks = $.Callbacks(); //~~建立事件处理中心 比较有用
callbacks.add();
callbacks.remove();
callbacks.fire();
callbacks.disable();
callbacks.empty();
callbacks.fired();
callbacks.fireWith(context, args);
callbacks.has(fn);
callbacks.lock();
callbacks.locked();

function fn1(a){
console.log(a);
}
function fn2(a){
console.log('fn2', a);
}

callbacks.add(fn1);
callbacks.add(fn2);
callbacks.fire('morning');


// $.Callbacks $.Deferred 和 pub/sub 模式,促进代码松耦合

用$.Callbacks()实现观察者模式

var observer = {
    hash: {},
    subscribe: function(id, callback) {
        if (typeof id !== 'string') {
            return
        }
        if (!this.hash[id]) {
            this.hash[id] = $.Callbacks()
            this.hash[id].add(callback)
        } else {
            this.hash[id].add(callback)
        }
    },
    publish: function(id) {
        if (!this.hash[id]) {
            return
        }
        this.hash[id].fire(id)
    }
}
 
// 订阅
observer.subscribe('mailArrived', function() {
    alert('来信了')
})
observer.subscribe('mailArrived', function() {
    alert('又来信了')
})
observer.subscribe('mailSend', function() {
    alert('发信成功')
})
 
// 发布
setTimeout(function() {
    observer.publish('mailArrived')
}, 5000)
setTimeout(function() {
    observer.publish('mailSend')
}, 10000)

 

$.Event解析
==============
$.Event(event/type, [props]); 返回可读写的jq事件对象 $event

$.event.fix(event); 在内部调用了$.Event构造函数,包装了原生事件对象

$.cache存储了全部注册的事件处理程序,实际上dom元素上的只有一个事件处理程序( $.cache[ele[$.expando]].handle , 其内部用 $.event.dispatch实现对缓存事件处理程序的访问)

$._data(domEle); 能够查看dom元素的数据缓存和绑定事件$(domEle).data(); 只能看到数据缓存