JQuery对Ajax的支持非常强大,使得用户借助JQuery可以轻松地完成许多ajax操作
1.Ajax调用
function sendAjaxMessage(){
alert("aa");
$.ajax({
type:"GET",
url:"BackService",
dataType:"json",
data:" ",
success:function(data,status){
alert("aaa" + data);
alert("result.name" + data.name);
alert("result.location" + data.location);
alert("result.sex" + data.sex);
}
});
}
$().ready(function(){
$(":button").bind("click",sendAjaxMessage);
})
在JQuery中,最底层的ajax调用就是JQuery.ajax,但是JQuery还提供了一些方便的快捷方法,如:$.get $.post $.load等减少用户的代码量,比如 $('#contents').load('hello-world.html'); 就是可以将hello-worl.html的内容用ajax的方式取回,并填充到 id为contents的控件中。
具体调用参数详查JQuery文档
2.关于Ajax的全局事件
ajaxStart
Triggered at the start of an Ajax request if no other requests are in progress
ajaxSend
Triggered before each individual request is sent
ajaxSuccess or ajaxError
Triggered upon a successful or an unsuccessful request
ajaxComplete
Triggered every time a request is complete (regardless of whether it was a success
or had an error)
ajaxStop
Triggered if there are no additional Ajax requests in progress
这些事件可以帮助我们是用户获得更好的体验
比如
(function($) {
$(document).ready(function() {
$('#loadingIndicator')
.bind('ajaxStart', function() {
$(this).show();
})
.bind('ajaxComplete', function() {
$(this).hide();
});
$.ajaxSetup({
cache: true,
dataType: 'json',
error: function(xhr, status, error) {
alert('An error occurred: ' + error);
},
timeout: 60000, // Timeout of 60 seconds
type: 'POST',
url: 'ajax-gateway.php'
}); // Close $.ajaxSetup()
}); // Close .read()
})(jQuery);
3.提交Form
// this tells the server-side process that Ajax was used
$('input[name="usingAJAX"]',this).val( 'true' );
// store reference to the form
var $this = $(this);
// grab the url from the form element
var url = $this.attr('action');
// prepare the form data to send
var dataToSend = $this.serialize();
// the callback function that tells us what the server-side process had to say
var callback = function(dataReceived){
// hide the form (thankfully we stored a reference to it)
$this.hide();
// in our case the server returned an HTML snippet so just append it to
// the DOM
// expecting: <div id="result">Your favorite food is pizza! Thanks for
// telling us!</div>
$('body').append(dataReceived)
};
// type of data to receive (in our case we're expecting an HTML snippet)
var typeOfDataToReceive = 'html';
// now send the form and wait to hear back
$.get( url, dataToSend, callback, typeOfDataToReceive )
}); // close .submit()