您好,欢迎访问一九零五行业门户网

从零开始学习jQuery (六) jquery中的AJAX使用_jquery

一.摘要本系列文章将带您进入jquery的精彩世界, 其中有很多作者具体的使用经验和解决方案,  即使你会使用jquery也能在阅读中发现些许秘籍.
本篇文章讲解如何使用jquery方便快捷的实现ajax功能.统一所有开发人员使用ajax的方式.
二.前言
ajax让用户页面丰富起来, 增强了用户体验. 使用ajax是所有web开发的必修课. 虽然ajax技术并不复杂, 但是实现方式还是会因为每个开发人员的而有所差异.jquery提供了一系列ajax函数来帮助我们统一这种差异, 并且让调用ajax更加简单.
三.原始ajax与jquery中的ajax
首先通过实例, 来看一下jquery实现ajax有多简单. 下面是一个使用原始ajax的示例:
doctype html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>html xmlns=http://www.w3.org/1999/xhtml>head> title>jquery ajaxtitle> > $(function() { var xhr = new ajaxxmlhttprequest(); $(#btnajaxold).click(function(event) { var xhr = new ajaxxmlhttprequest(); xhr.onreadystatechange = function() { if (xhr.readystate == 4) { document.getelementbyid(divresult).innerhtml = xhr.responsetext; } } xhr.open(get, data/ajaxgetcityinfo.aspx?resulttype=html, true); xhr.send(null); }); }) //跨浏览器获取xmlhttprequest对象 function ajaxxmlhttprequest() { var xmlhttp; try { // firefox, opera 8.0+, safari xmlhttp = new xmlhttprequest(); } catch (e) { // internet explorer try { xmlhttp = new activexobject(msxml2.xmlhttp); } catch (e) { try { xmlhttp = new activexobject(microsoft.xmlhttp); } catch (e) { alert(您的浏览器不支持ajax!); return false; } } } return xmlhttp; } script>head>body> button id=btnajaxold>原始ajax调用button>br /> br /> div id=divresult>div>body>html>
上面的实例中, data/ajaxgetcityinfo.aspx?resulttype=html 地址会返回一段html代码.
使用原始ajax, 我们需要做较多的事情, 比如创建xmlhttprequest对象,  判断请求状态, 编写回调函数等.
而用jquery的load方法, 只需要一句话:
$(#divresult).load(data/ajaxgetcityinfo.aspx, { resulttype: html });
曾经我是一个原始ajax的绝对拥护者, 甚至摒弃微软的asp.net ajax, 因为我想要最高的代码灵活度. 使用原始ajax让我感觉完成自己的工作更加轻松, 即使多写了一些代码. 但是当我去翻看别人的ajax代码并且尝试修改的时候, 我改变了我的看法--我们的代码到处分布着创建xmlhttprequest方法的函数, 或者某些ajax程序逻辑性和结构性很差, 很难看懂.
我们可以将通用方法放到一个js文件中, 然后告诉大家嘿伙伴们, 都来用这个js中的方法. 但是在某些时候有些新来的外包人员并不知道有这个js文件的存在. 而且其实这个通用的js就是一个公共的脚本类库,  我相信没有人会觉得自己开发一个类库会比jquery更好!
所以我放弃了制造轮子的计划,  大家都使用jquery编写ajax相关的方法就可以解决各种差异性问题, 并且让工作更有效率.
现在只是用jquery的ajax函数, 我的页面变得简洁了:
doctype html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>html xmlns=http://www.w3.org/1999/xhtml>head> title>jquery ajaxtitle> script type=text/javascript src=scripts/jquery-1.3.2-vsdoc2.js>script> > $(function() { $(#btnajaxjquery).click(function(event) { $(#divresult).load(data/ajaxgetcityinfo.aspx, { resulttype: html }); }); }) script>head>body> button id=btnajaxjquery>使用jquery的load方法button> br /> div id=divresult>div>body>html>
四.jquery ajax详解
jquery提供了几个用于发送ajax请求的函数. 其中最核心也是最复杂的是jquery.ajax( options ),所有的其他ajax函数都是它的一个简化调用. 当我们想要完全控制ajax时可以使用此结果, 否则还是使用简化方法如get, post, load等更加方便. 所以jquery.ajax( options ) 方法放到最后一个介绍. 先来介绍最简单的load方法:
1.  load( url, [data], [callback] )returns: jquery包装集
说明:
load方法能够载入远程 html 文件代码并插入至 dom 中。
默认使用 get 方式, 如果传递了data参数则使用post方式.
- 传递附加参数时自动转换为 post 方式。jquery 1.2 中,可以指定选择符,来筛选载入的 html 文档,dom 中将仅插入筛选出的 html 代码。语法形如 url #some > selector, 默认的选择器是body>*.
讲解:
load是最简单的ajax函数, 但是使用具有局限性:
它主要用于直接返回html的ajax接口 load是一个jquery包装集方法,需要在jquery包装集上调用,并且会将返回的html加载到对象中, 即使设置了回调函数也还是会加载. 不过不可否认load接口设计巧妙并且使用简单.下面通过示例来演示load接口的使用:
doctype html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>html xmlns=http://www.w3.org/1999/xhtml>head> title>jquery ajax - loadtitle> script type=text/javascript src=../scripts/jquery-1.3.2-vsdoc2.js>script> > $(function() { $(#btnajaxget).click(function(event) { //发送get请求 $(#divresult).load(../data/ajaxgetmethod.aspx?param=btnajaxget_click + ×tamp= + (new date()).gettime()); }); $(#btnajaxpost).click(function(event) { //发送post请求 $(#divresult).load(../data/ajaxgetmethod.aspx, { param: btnajaxpost_click }); }); $(#btnajaxcallback).click(function(event) { //发送post请求, 返回后执行回调函数. $(#divresult).load(../data/ajaxgetmethod.aspx, { param: btnajaxcallback_click }, function(responsetext, textstatus, xmlhttprequest) { responsetext = add in the callback function!
+ responsetext $(#divresult).html(responsetext); //或者: $(this).html(responsetext); }); }); $(#btnajaxfilthtml).click(function(event) { //发送get请求, 从结果中过滤掉 鞍山 这一项 $(#divresult).load(../data/ajaxgetcityinfo.aspx?resulttype=html + ×tamp= + (new date()).gettime() + ul>li:not(:contains('鞍山'))); }); }) script>head>body> button id=btnajaxget>使用load执行get请求button>br /> button id=btnajaxpost>使用load执行post请求button>br /> button id=btnajaxcallback>使用带有回调函数的load方法button>br /> button id=btnajaxfilthtml>使用selector过滤返回的html内容button> br /> div id=divresult>div>body>html>


上面的示例演示了如何使用load方法.
提示:我们要时刻注意浏览器缓存,  当使用get方式时要添加时间戳参数 (net date()).gettime() 来保证每次发送的url不同, 可以避免浏览器缓存.
提示: 当在url参数后面添加了一个空格, 比如  的时候, 会出现无法识别符号的错误, 请求还是能正常发送. 但是无法加载html到dom. 删除后问题解决.
2.jquery.get( url, [data], [callback], [type] ) returns: xmlhttprequest
说明:
通过远程 http get 请求载入信息。
这是一个简单的 get 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
讲解:
此函数发送get请求, 参数可以直接在url中拼接, 比如:
$.get(../data/ajaxgetmethod.aspx?param=btnajaxget_click);
或者通过data参数传递:
$.get(../data/ajaxgetmethod.aspx, { param: btnajaxget2_click });


两种方式效果相同, data参数会自动添加到请求的url中
如果url中的某个参数, 又通过data参数传递, 不会自动合并相同名称的参数.
回调函数的签名如下:
function (data, textstatus) { // data could be xmldoc, jsonobj, html, text, etc... this; // the options for this ajax request}
其中data是返回的数据, teststatus表示状态码, 可能是如下值:
timeout,error,notmodified,success,parsererror
在回调函数中的this是获取options对象的引用.有关options的各种说明, 请参见:
http://docs.jquery.com/ajax/jquery.ajax#options

type参数是指data数据的类型, 可能是下面的值:
xml, html, script, json, jsonp, text.
默认为html.
jquery.getjson( url, [data], [callback] ) 方法就相当于 jquery.get(url, [data],[callback], json)
3. jquery.getjson( url,  [data], [callback] )returns: xmlhttprequest
相当于:   jquery.get(url, [data],[callback], json)
说明:
通过 http get 请求载入 json 数据。
在 jquery 1.2 中,您可以通过使用jsonp 形式的回调函数来加载其他网域的json数据,如 myurl?callback=?。jquery 将自动替换 ? 为正确的函数名,以执行回调函数。
注意:此行以后的代码将在这个回调函数执行前执行。
讲解:
getjson函数仅仅将get函数的type参数设置为json而已. 在回调函数中获取的数据已经是按照json格式解析后的对象了:
$.getjson(../data/ajaxgetcityinfo.aspx, { resulttype: json }, function(data, textstatus){ alert(data.length); alert(data[0].cityname);});
服务器端返回的字符串如下:
[{pkid:0997,provinceid:xj,cityname:阿克苏,citynameen:akesu,postcode:843000,ishotcity:false}, {pkid:0412,provinceid:ln,cityname:鞍山,citynameen:anshan,postcode:114000,ishotcity:false}]
示例中我返回的饿是一个数组, 使用data.length可以获取数组的元素个数,  data[0]访问第一个元素, data[0].cityname访问第一个元素的cityname属性.
4.jquery.getscript( url, [callback] )returns: xmlhttprequest
相当于:   jquery.get(url, null, [callback], script)
说明:
通过 http get 请求载入并执行一个 javascript 文件。
jquery 1.2 版本之前,getscript 只能调用同域 js 文件。 1.2中,您可以跨域调用 javascript 文件。注意:safari 2 或更早的版本不能在全局作用域中同步执行脚本。如果通过 getscript 加入脚本,请加入延时函数。
讲解:
以前我使用dojo类库时官方默认的文件不支持跨域最后导致我放弃使用dojo(虽然在网上找到了可以跨域的版本, 但是感觉不够完美).  所以我特别对这个函数的核心实现和使用做了研究.
首先了解此函数的jquery内部实现, 仍然使用get函数, jquery所有的ajax函数包括get最后都是用的是jquery.ajax(), getscript将传入值为script的type参数,  最后在ajax函数中对type为script的请求做了如下处理:
var head = document.getelementsbytagname(head)[0]; var script = document.createelement(script);script.src = s.url;
上面的代码动态建立了一个script语句块, 并且将其加入到head中:
head.appendchild(script);
当脚本加载完毕后, 再从head中删除:
// handle script loading if ( !jsonp ) { var done = false; // attach handlers for all browsers script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readystate || this.readystate == loaded || this.readystate == complete) ) { done = true; success(); complete(); // handle memory leak in ie script.onload = script.onreadystatechange = null; head.removechild( script ); } }; }
我主要测试了此函数的跨域访问和多浏览器支持.下面是结果:
ie6 firefox 注意事项
非跨域引用js 通过 通过 回调函数中的data和textstatus均可用
跨域引用js 通过 通过 回调函数中的data和textstatus均为undifined
下面是我关键的测试语句, 也用来演示如何使用getscript函数:
$(#btnajaxgetscript).click(function(event) { $.getscript(../scripts/getscript.js, function(data, textstatus) { alert(data); alert(textstatus); alert(this.url); }); }); $(#btnajaxgetscriptcross).click(function(event) { $.getscript(http://resource.elong.com/getscript.js, function(data, textstatus) { alert(data); alert(textstatus); alert(this.url); }); });


5. jquery.post( url, [data], [callback], [type] )returns: xmlhttprequest
说明:
通过远程 http post 请求载入信息。
这是一个简单的 post 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
讲解:
具体用法和get相同, 只是提交方式由get改为post.
6. jquery.ajax( options )returns: xmlhttprequest
说明:
通过 http 请求加载远程数据。
jquery 底层 ajax 实现。简单易用的高层实现见 $.get, $.post 等。
$.ajax() 返回其创建的 xmlhttprequest 对象。大多数情况下你无需直接操作该对象,但特殊情况下可用于手动终止请求。
$.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息。详细参数选项见下。
注意: 如果你指定了 datatype 选项,请确保服务器返回正确的 mime 信息,(如 xml 返回 text/xml)。错误的 mime 类型可能导致不可预知的错误。见 specifying the data type for ajax requests 。
注意:如果datatype设置为script,那么所有的远程(不在同一域名下)的post请求都将转化为get请求。(因为将使用dom的script标签来加载)
jquery 1.2 中,您可以跨域加载 json 数据,使用时需将数据类型设置为 jsonp。使用 jsonp 形式调用函数时,如 myurl?callback=? jquery 将自动替换 ? 为正确的函数名,以执行回调函数。数据类型设置为 jsonp 时,jquery 将自动调用回调函数。
讲解:
这是jquery中ajax的核心函数, 上面所有的发送ajax请求的函数内部最后都会调用此函数.options参数支持很多参数, 使用这些参数可以完全控制ajax请求. 在ajax回调函数中的this对象也是options对象.
因为平时使用最多的还是简化了的get和post函数, 所以在此不对options参数做详细讲解了. options参数文档请见:
http://docs.jquery.com/ajax/jquery.ajax#options
五.ajax相关函数.jquery提供了一些相关函数能够辅助ajax函数.
1. jquery.ajaxsetup( options )无返回值
说明:
设置全局 ajax 默认options选项。
讲解:
有时我们的希望设置页面上所有ajax属性的默认行为.那么就可以使用此函数设置options选项, 此后所有的ajax请求的默认options将被更改.
options是一个对象, 可以设置的属性请此连接:http://docs.jquery.com/ajax/jquery.ajax#toptions
比如在页面加载时, 我使用下面的代码设置ajax的默认option选项:
$.ajaxsetup({ url: ../data/ajaxgetmethod.aspx, data: { param: ziqiu.zhang }, global: false, type: post, success: function(data, textstatus) { $(#divresult).html(data); } });
上面的代码设置了一个ajax请求需要的基本数据: 请求url, 参数, 请求类型, 成功后的回调函数.
此后我们可以使用无参数的get(), post()或者ajax()方法发送ajax请求.完整的示例代码如下:
doctype html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>html xmlns=http://www.w3.org/1999/xhtml>head> title>jquery ajax - loadtitle> script type=text/javascript src=../scripts/jquery-1.3.2-vsdoc2.js>script> > $(document).ready(function() { $.ajaxsetup({ url: ../data/ajaxgetmethod.aspx, data: { param: ziqiu.zhang }, global: false, type: post, success: function(data, textstatus) { $(#divresult).html(data); } }); $(#btnajax).click(function(event) { $.ajax(); }); $(#btnget).click(function(event) { $.get(); }); $(#btnpost).click(function(event) { $.post(); }); $(#btnget2).click(function(event) { $.get(../data/ajaxgetmethod.aspx,{ param: other }); }); }); script>head> body> button id=btnajax>不传递参数调用ajax()方法button>br /> button id=btnget>不传递参数调用get()方法button>br /> button id=btnpost>不传递参数调用post()方法button>br /> button id=btnget2>传递参数调用get()方法, 使用全局的默认回调函数button>br /> br /> div id=divresult>div>body>html>
注意当使用get()或者post()方法时, 除了type参数将被重写为get或者post外, 其他参数只要不传递都是使用默认的全局option. 如果传递了某一个选项, 比如最后一个按钮传递了url和参数, 则本次调用会以传递的选项为准. 没有传递的选项比如回调函数还是会使用全局option设置值.
2.serialize( )returns: string
说明:
序列表表格内容为字符串,用于 ajax 请求。
序列化最常用在将表单数据发送到服务器端时. 被序列化后的数据是标准格式, 可以被几乎所有的而服务器端支持.
为了尽可能正常工作, 要求被序列化的表单字段都有name属性, 只有一个eid是无法工作的.
像这样写name属性:
input id=email name=email type=text />
讲解:
serialize()函数将要发送给服务器的form中的表单对象拼接成一个字符串. 便于我们使用ajax发送时获取表单数据. 这和一个from按照get方式提交时, 自动将表单对象的名/值放到url上提交差不多.
比如这样一个表单:
生成的字符串为:single=single¶m=multiple¶m=multiple3&check=check2&radio=radio1
提示:代码见 chapter6\7-serialize.htm
3.serializearray( )returns: arrayobject>
说明:
序列化表格元素 (类似 '.serialize()' 方法) 返回 json 数据结构数据。
注意,此方法返回的是json对象而非json字符串。需要使用插件或者第三方库进行字符串化操作。
讲解:
看说明文档让我有所失望, 使用此函数获取到的是json对象, 但是jquery中没有提供将json对象转化为json字符串的方法.
在json官网上没有找到合适的json编译器, 最后选用了jquery.json这个jquery插件:
http://code.google.com/p/jquery-json/
使用起来异常简单:
var thing = {plugin: 'jquery-json', version: 1.3};var encoded = $.tojson(thing); //'{plugin: jquery-json, version: 1.3}'var name = $.evaljson(encoded).plugin; //jquery-jsonvar version = $.evaljson(encoded).version; // 1.3
使用serializearray( ) 再配合 $.tojson 方法, 我们可以很方便的获取表单对象的json, 并且转换为json字符串:
$(#results).html( $.tojson( $(form).serializearray() ));
结果为:
[{name: single, value: single}, {name: param, value: multiple}, {name: param, value: multiple3}, {name: check, value: check2}, {name: radio, value: radio1}]
六.全局ajax事件在jquery.ajaxsetup( options ) 中的options参数属性中, 有一个global属性:
global
类型:布尔值
默认值: true
说明:是否触发全局的ajax事件.
这个属性用来设置是否触发全局的ajax事件. 全局ajax事件是一系列伴随ajax请求发生的事件.主要有如下事件:
名称 说明
ajaxcomplete( callback ) ajax 请求完成时执行函数
ajaxerror( callback ) ajax 请求发生错误时执行函数
ajaxsend( callback ) ajax 请求发送前执行函数
ajaxstart( callback ) ajax 请求开始时执行函数
ajaxstop( callback ) ajax 请求结束时执行函数
ajaxsuccess( callback ) ajax 请求成功时执行函数
用一个示例讲解各个事件的触发顺序:
doctype html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>html xmlns=http://www.w3.org/1999/xhtml>head> title>jquery ajax - ajaxeventtitle> script type=text/javascript src=../scripts/jquery-1.3.2.min.js>script> > $(document).ready(function() { $(#btnajax).bind(click, function(event) { $.get(../data/ajaxgetmethod.aspx); }) $(#divresult).ajaxcomplete(function(evt, request, settings) { $(this).append('ajaxcomplete
'); }) $(#divresult).ajaxerror(function(evt, request, settings) { $(this).append('ajaxerror
'); }) $(#divresult).ajaxsend(function(evt, request, settings) { $(this).append('ajaxsend
'); }) $(#divresult).ajaxstart(function() { $(this).append('ajaxstart
'); }) $(#divresult).ajaxstop(function() { $(this).append('ajaxstop
'); }) $(#divresult).ajaxsuccess(function(evt, request, settings) { $(this).append('ajaxsuccess
'); }) }); script>head>body> br />button id=btnajax>发送ajax请求button>br/> div id=divresult>div>body>html>
结果如图:
我们可以通过将默认options的global属性设置为false来取消全局ajax事件的触发.
七.注意事项如果在get请求发送的url中有两个同名参数, 比如两个param参数:
http://localhost/ajaxgetmethod.aspx?param=multiple¶m=multiple3
使用服务器端方法获取param参数:
if (!string.isnullorempty(httpcontext.current.request[param])) { param = httpcontext.current.request[param]; }
此时获取到得param是一个用,分隔多个值的字符串:
multiple,multiple3

八.总结本文介绍如何使用jquery实现ajax功能.  用于发送ajax请求的相关函数如load, get, getjson和post这些渐变ajax方法, 对于核心的ajax 方法没有过多介绍, 主要是通过配置复杂的参数实现完全控制ajax请求. 另外讲解了ajax的辅助函数比如用于序列化表单对象为字符串的serialize()方法, 用于将表单对象序列化为json对象的serializearray()方法. 这些在使用脚本获取数据实现与服务器端交互是很有用, json格式的数据在处理大对象编程时将我们从混乱的属性字符串中解放出来.
jquery还提供录入全局ajax事件这一个特殊的事件, 并且可以在一个对象上设置这些事件, 在发送ajax请求的各个生命周期上会调用这些事件, 可以通过修改默认的options对象的global属性打开或关闭全局事件.
目前本系列文章在加紧创作阶段. 所以代码和文章示例都没有来得及重新整理. 下面是本章的代码下载, 但是含有所有以前未整理的示例,请大家下载后看chapter6文件夹, 里面是本章的所有示例:
http://xiazai.jb51.net/201101/yuanma/code-jquerystudy.rar
其它类似信息

推荐信息