jQuery Ajax 事件
Ajax请求会产生若干不同的事件,我们可以订阅这些事件并在其中处理我们的逻辑。在jQuery这里有两种Ajax事件:局部事件 和 全局事件。
局部事件就是在每次的Ajax请求时在方法内定义的,例如:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event }, complete: function(){
// Handle the complete event } // ... });
全局事件是每次的Ajax请求都会触发的,它会向DOM中的所有元素广播,在上面 getScript() 示例中加载的脚本就是全局Ajax事件。全局事件可以如下定义:
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
或者:
$("#loading").ajaxStart(function(){
$(this).show();
});
我们可以在特定的请求将全局事件禁用,只要设置下 global 选项就可以了:
$.ajax({
url: "test.html",
global: false,// 禁用全局Ajax事件. // ... });
下面是jQuery官方给出的完整的Ajax事件列表:
- ajaxStart (Global Event)
This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.- 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)
This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
- beforeSend (Local Event)
- ajaxStop (Global Event)
This global event is triggered if there are no more Ajax requests being processed.具体的全局事件请参考API文档。
好了,下面开始说jQuery里面功能最强的Ajax请求方法 $.ajax();jQuery.ajax( options ) : 通过 HTTP 请求加载远程数据
这个是jQuery 的底层 AJAX 实现。简单易用的高层实现见 $.get, $.post 等。
$.ajax() 返回其创建的 XMLHttpRequest 对象。大多数情况下你无需直接操作该对象,但特殊情况下可用于手动终止请求。
注意: 如果你指定了 dataType 选项,请确保服务器返回正确的 MIME 信息,(如 xml 返回 "text/xml")。错误的 MIME 类型可能导致不可预知的错误。见 Specifying the Data Type for AJAX Requests 。
当设置 datatype 类型为 'script' 的时候,所有的远程(不在同一个域中)POST请求都回转换为GET方式。$.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息。详细参数选项见下。
jQuery 1.2 中,您可以跨域加载 JSON 数据,使用时需将数据类型设置为 JSONP。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。数据类型设置为 "jsonp" 时,jQuery 将自动调用回调函数。(这个我不是很懂)
参数列表:
参数名 类型 描述 url String (默认: 当前页地址) 发送请求的地址。 type String (默认: "GET") 请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。 timeout Number 设置请求超时时间(毫秒)。此设置将覆盖全局设置。 async Boolean (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。 beforeSend Function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。
function (XMLHttpRequest) {
this; // the options for this ajax request }cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。 complete Function 请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。
function (XMLHttpRequest, textStatus) {
this; // the options for this ajax request }contentType String (默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。 data Object,
String发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。 dataType String 预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:
"xml": 返回 XML 文档,可用 jQuery 处理。
"html": 返回纯文本 HTML 信息;包含 script 元素。
"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。
"json": 返回 JSON 数据 。
"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
error Function (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。
function (XMLHttpRequest, textStatus, errorThrown) {
// 通常情况下textStatus和errorThown只有其中一个有值 this; // the options for this ajax request }global Boolean (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件 ifModified Boolean (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。 processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。 success Function 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }这里有几个Ajax事件参数:beforeSend ,success ,complete ,error 。我们可以定义这些事件来很好的处理我们的每一次的Ajax请求。注意一下,这些Ajax事件里面的 this 都是指向Ajax请求的选项信息的(请参考说 get() 方法时的this的图片)。
请认真阅读上面的参数列表,如果你要用jQuery来进行Ajax开发,那么这些参数你都必需熟知的。
-
原文章:http://www.cnblogs.com/yeer/archive/2009/07/23/1529460.html
-
JS xmlhttprequest
-
用js内置对象XMLHttpRequest 来用ajax
步骤:
/* 用XMLHTTPRequest来进行ajax异步数据交交互*/
主要有几个步骤:
//1.创建XMLHTTPRequest对象
//最复杂的一步
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
//针对某些特定版本的mozillar浏览器的bug进行修正。
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType('text/xml');
};
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}2.注册回调函数
xmlhttp.onreadystatechange = callback;
//3.设置连接信息。
//open第一个参数链接方式,第二是url地址
//3,true是异步链接
//xmlhttp.open("GET","xhr.php?name=" + username,true);//使用post方式发送数据
xmlhttp.open("POST","xhr.php",true);//post需要自己设置http的请求头
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//4,发送数据,开始和服务器进行交互
//中如果true, send这句话会立即执行
//如果是false(同步),send会在服务器数据回来才执行
//xmlhttp.send(null);
//因为是get所以send中不需要内容
xmlhttp.send('name=' +username);}
//5.写回调函数,不同相应状态进行处理function callback(){
alert(xmlhttp.readyState);
//判断对象状态是交互完成,接收服务器返回的数据
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//["dada","xiaoyin","liujie"]
//纯文本的数据
var responseText = xmlhttp.responseText;
var divNode = document.getElementById('result');
//6.将服务器的数据显示在客户端
divNode.innerHTML = responseText;
}
}新加:设置编码方法
setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=gb2312")
语法
oXMLHttpRequest.setRequestHeader(bstrHeader, bstrValue);
参数
bstrHeader 字符串,头名称。
bstrValue 字符串,值。
还是不很明白
1、XMLObject.setRequestHeader "CONTENT-TYPE", "application/x-www-form-urlencoded"
CONTENT-TYPE是什么意思,application/x-www-form-urlencoded是什么意思?
2、下面几句setRequestHeader的含义?
setRequestHeader("Content-type", "application/x-www-form-urlencoded");
setRequestHeader("Content-length", paramsSend.length);
setRequestHeader("Connection", "close");
解答:
通常在HTTP协议里,客户端像服务器取得某个网页的时候,必须发送一个HTTP协议的头文件,
告诉服务器客户端要下载什么信息以及相关的参数,如:
GET /bb.asp?www=1234 HTTP/1.1
Accept: */*
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
Host: www.e4j.cn:89
Connection: Keep-Alive
Cookie: %C3%F7%CC%EC=%B0%CB;ASPSESSIONIDASDBSDRR=BLEDBIBBCGKBJAKJCFEJKGII而 XMLHTTP 就是通过HTTP协议取得网站上的文件数据的,所以也要发送HTTP头给服务器。
但是 XMLHTTP 默认的情况下有些参数可能没有说明在HTTP头里,这是当我们需要修改或添加这些参数时就用到了setRequestHeader 方法。
就比如如果上面这段HTTP头文件内容是 XMLHTTP 提交默认的情况,当使用 setRequestHeader 方法后就这样,如:
XMLObject.setRequestHeader "CONTENT-TYPE", "application/x-www-form-urlencoded"
setRequestHeader "Connection", "close"
这时HTTP头信息就应该是这样了:
GET /bb.asp?www=1234 HTTP/1.1
Accept: */*
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
CONTENT-TYPE:application/x-www-form-urlencoded
Host: www.e4j.cn:89
Connection: close
Cookie: %C3%F7%CC%EC=%B0%CB;ASPSESSIONIDASDBSDRR=BLEDBIBBCGKBJAKJCFEJKGIIsetRequestHeader方法只是XMLHTTP为添加或修改HTTP头提供的一个接口方法而已,
至于里面的值则是HTTP协议的含义,当然也可以发自己的东西进去,即使IIS不能识别你的信息也不会报错如: setRequestHeader "MyName", "Supermanking"
虽然IIS不会报错,但这个信息也可以有用,可以在ASP程序里读取HTTP头信息分析是否有
MyName: Supermanking 信息,可根据你的需求来做处理,还有,CONTENT-TYPE:application/x-www-form-urlencoded含义是表示客户端提交给服务器文本内容的编码方式是URL编码,即除了标准字符外,每字节以双字节16进制前加个“%”表示当然还有其他编码方式,如:CONTENT-TYPE:multipart/form-data
至于:Content-length 就是表示提交的数据字节大小
http有几种提交方式,其中比较常用的就是 GET 和 POST
这个标志就放在HTTP头开头的地方,这样讲容易理解点
GET 方式是没有提交内容的,所以 Content-length 在 GET 模式下是无效的.
GET 传参数的方式就是通过虚拟地址传送,如:
GET /bb.asp?www=1234 HTTP/1.1
参数全部就只有 "www=1234" 这么多如果用POST的话就有些不同,POST是将参数放到HTTP后面的,就以上面的HTTP作范例,用POST的方法传参数
原文地址:http://blog.youkuaiyun.com/iamduoluo/article/details/7215639
POST /bb.asp HTTP/1.1
Accept: */*
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
CONTENT-TYPE:application/x-www-form-urlencoded
Host: www.e4j.cn:89
Content-length: 8
Connection: close
Cookie: %C3%F7%CC%EC=%B0%CB;ASPSESSIONIDASDBSDRR=BLEDBIBBCGKBJAKJCFEJKGII
www=1234
这时,数据就需要说明字节大小了
至于 Connection: Close,很明显英文的意思是 连接:关闭
只是客户端在提交数据时告诉服务器让谁先关闭连接而已。 -
实例应用:
-