jQuery.ajax( options ) Returns: XMLHttpRequest
example:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
以上options写了许多属性, 一看也能明白它们的含义。不过显得有些麻烦了,于是就有了简化版本:
jQuery.post( url, [data], [callback] ) Returns: XMLHttpRequest
以上的code就可以写成:
$post("some.php","name=John&location=Boston",function(msg){
alert( "Data Saved: " + msg );
});
除了post,当然还有get:
jQuery.get( url, [data], [callback] ) Returns: XMLHttpRequest
比较特殊的,还有:
jQuery.getJSON( url, [data], [callback] ) Returns: XMLHttpRequest
以get方式,从服务端获取json对象。get和post其实返回对象也可以是json, html,xml,json都行,因此这个方法感觉有些多余了, 实际用处应该不大。
还有一个特殊方式
jQuery.getScript( url, [callback] ) Returns: XMLHttpRequest
url指定了一个javascript脚本, 当脚本加载完毕则执行callback。这个形式不像前面都是异步请求返回业务需要的数据, 这里是动态加载javascript, 比较有意思。
sample:
$(document).ready(function(){
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
Ajax Events:
ajax事件分了两种:local和global, local的是对ajax调用本身而言的,而global可以将事件注册到dom组件上。
local event:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ...
});
beforeSend和complete都是ajax调用中内部的事件,因此不可以绑定到其他组件。
global event:
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
ajaxSend是global的,因此既可以在ajax内部使用,也能绑定在dom元素之上。
global事件是可以禁止的:
$.ajax({
url: "test.html",
global: false,
// ...
});
事件类型还有一个规律, 凡是带了ajax开头的都是global的,否则就是local的。
而且几乎总有一个global事件跟local事件对应。
# beforeSend (Local Event)
This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
# ajaxSend (Global Event)
This global event is also triggered before the request is run.
# success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
# ajaxSuccess (Global Event)
This event is also only called if the request was successful.
# error (Local Event)
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
# ajaxError (Global Event)
This global event behaves the same as the local error event.
# complete (Local Event)
This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
# ajaxComplete (Global Event)
事件响应function基本都是如此:
function (event, XMLHttpRequest, ajaxOptions) {
this; // dom element listening
}
对于error的,最后还多一个thrownError参数
当需要调整某个ajax请求的参数的时候,ajaxSetup能够派上用场:
$.ajaxSetup({
url: "/xmlhttp/",
global: false,
type: "POST"
});