一、jQuery的Ajax方法
jQuery对Ajax 做了大量的封装,使用起来也较为方便,不需要去考虑浏览器兼容性。对于封装的方式,jQuery 采用了三层封装:
- 最底层的封装方法为——$.ajax()
- 而通过这层封装了第二层有三种方法——.load()、$.get()和$.post()
- 最高层是——$.getScript()和$.getJSON()方法
1.1 .load()方法 —— 载入远程 HTML 文件代码并插入至 DOM 中
load(url, [data], [callback])
- load是局部方法,需要一个包含元素的jQuery 对象作为前缀,对于用途而言,.load()适合做静态文件的异步获取
- url:待装入 HTML 网页网址。
- data:发送至服务器的 key/value 数据。在jQuery 1.3中也可以接受一个字符串了。向服务器提交数据有两种方式:get 和post。
//不传递data,则默认get 方式,data使用?方式 $('input').click(function () { $('#box').load('test.php?url=ycku'); }); //传递data,则为post 方式,data必须使用键值对方式 $('input').click(function () { $('#box').load('test.php', { url : 'ycku' }); });
- callback:载入成功时回调函数,其参数如下图
回调函数callback也可以传递三个可选参数:
- responseText(请求返回):
- status(请求状态): 如果成功返回数据则为:success,否则为:error
- XMLHttpRequest(XMLHttpRequest 对象):否则为:error
$('input').click(function () {
$('#box').load('test.php', {
url : 'ycku'
}, function (response, status, xhr) {
alert('返回的值为:' + response + ',状态为:' + status + ',状态是:' + xhr.statusText);
});
});
1.2 $.get()和$.post()
jQuery.get(url, [data], [callback], [type])
jQuery.post(url, [data], [callback], [type])
- $.get()和$.post()是全局方法,无须指定某个元素。对于用途而言,.load()适合做静态文件的异步获取,
而对于需要传递参数到服务器页面的,$.get()和$.post()更加合适 - url:发送请求地址。
- data:待发送 Key/value参数
//通过直接在url问号紧跟传参 $('input').click(function () { $.get('test.php', 'url=ycku',function (response, status, xhr) { $('#box').html(response); }); }); //通过第二个参数data,字符串形式的键值对传参,然后自动转换为问号紧跟传参 $('input').click(function () { $.get('test.php', { url : 'ycku' },function (response, status, xhr) { $('#box').html(response); }); }); //通过第二个参数data,对象形式的键值对传参,然后自动转换为问号紧跟传参 $('input').click(function () { $.post('test.php?url=ycku', function (response, status, xhr) { $('#box').html(response); }); }); //post提交不能使用问号传参 $('input').click(function () { $.post('test.php', 'url=ycku',function (response, status, xhr) { $('#box').html(response); }); }); //post提交可以使用字符串形式的键值对传参,自动转换为http消息实体传参 $('input').click(function () { $.post('test.php', { url : 'ycku' },function (response, status, xhr) { $('#box').html(response); }); }); //post提交可以使用对象键值对 $('input').click(function () { $.post('test.php', { url : 'ycku' },function (response, status, xhr) { $('#box').html(response); }, 'html'); //PHP文件返回的数据是纯文本,默认是html或text });