jQuery ajax(复习)—Baidu ajax request分离版
2024-05-06 14:19:47
供稿:网友
你没有看错标题,本文的确是在讲Baidu ajax,不过是很久很久以前的版本了。
由于jQuery ajax模块有800+行,而核心函数jQuery.ajax就有380+行,直接分析这段代码很容易被代码逻辑弄晕。
所以我们先分析一段简单的ajax代码,来自早期的百度七巧板项目。
通过这个来先复习一遍ajax的知识。
baidu.ajax.request分离版
代码如下:
/**
* 发送一个ajax请求
* @author: allstar, erik, berg
* @name ajax.request
* @function
* @grammar ajax.request(url[, options])
* @param {string} url 发送请求的url
* @param {Object} options 发送请求的选项参数
* @config {String} [method] 请求发送的类型。默认为GET
* @config {Boolean} [async] 是否异步请求。默认为true(异步)
* @config {String} [data] 需要发送的数据。如果是GET请求的话,不需要这个属性
* @config {Object} [headers] 要设置的http request header
* @config {number} [timeout] 超时时间,单位ms
* @config {String} [username] 用户名
* @config {String} [password] 密码
* @config {Function} [onsuccess] 请求成功时触发,function(XMLHttpRequest xhr, string responseText)。
* @config {Function} [onfailure] 请求失败时触发,function(XMLHttpRequest xhr)。
* @config {Function} [onbeforerequest] 发送请求之前触发,function(XMLHttpRequest xhr)。
*
* @meta standard
* @see ajax.get,ajax.post
*
* @returns {XMLHttpRequest} 发送请求的XMLHttpRequest对象
*/
var ajax = {};
ajax.request = function(url,options,type){
// 是否需要异步
var async = options.async||true,
// 用户名、密码
username = options.username||"",
password = options.password||"",
// 需要传输的数据
data = options.data||"",
// GET还是POST
method = (options.method||"GET").toUpperCase(),
// 请求头
headers = options.headers||{},
// 事件处理函数表
eventHandler = {},
// 请求数据类型
dataType = type||"string";//xml||string
function stateChangeHandler(){
// 看看是否已经准备好了
if(xhr.readyState == 4){
// 得到xhr当前状态
var sta = xhr.status;
// 判断是否成功
if(sta == 200||sta == 304){
// 成功则触发成功
fire("success");
}else{
// 失败则触发失败
fire("failure");
}
// 清除绑定
window.setTimeout(function(){
xhr.onreadystatechange= new Function();
if (async){
xhr = null;
}
},0);
}
}
function fire(type){
// 把type变成ontype
type = "on"+type;
// 在事件处理器表中找到对应事件的处理函数
var handler = eventHandler[type];
// 如果函数存在,则
if(handler){
// 不成功的话
if(type != "onsuccess"){
handler(xhr);
// 成功了
}else{
// 则根据dataType返回不同的数据
handler(xhr,dataType!="xml"?xhr.responseText:xhr.responseXML);
}