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

jQuery的实现原理的模拟代码 -5 Ajax_jquery

复制代码 代码如下:
// 创建 xhr 对象
var xhr;
if (window.xmlhttprequest) {
xhr = new xmlhttprequest();
}
else if (window.activexobject) {
xhr = new activexobject(msxml2.xmlhttp);
}
else {
throw new error(ajax is not supported by this browser);
}
function ready()
{
alert(start......);
// 通过事件来处理异步请求
xhr.onreadystatechange = function()
{
if( xhr.readystate == 4 )
{
alert( ready.);
if( xhr.status == 200 )
{
alert(成功获得服务器返回的结果.);
// 请求结束之后,可以获取服务器返回的内容
alert( xhr.responsetext );
// 获取服务器返回的 json 对象
var alice = eval( ( + xhr.responsetext + ) );
alert( alice.name );
}
}
};
// 设置请求参数
xhr.open(get, data.json );
xhr.send( null );
}
jquery 简单地包装了对 xhr 对象的使用,通过对 jquery 对象增加常用的访问方法,然后,提供给 jquery 对象来使用。
复制代码 代码如下:
// 主要的扩展在 jquery.ajax 中。
jquery.extend({ // #6299
// 请求的默认参数
ajaxsettings: {
url: location.href,
type: get,
contenttype: application/x-www-form-urlencoded,
data: null,
xhr: window.xmlhttprequest && (window.location.protocol !== file: || !window.activexobject) ?
function () {
return new window.xmlhttprequest();
} :
function () {
try {
return new window.activexobject(microsoft.xmlhttp);
} catch (e) { }
}
},
// 用来设置 jquery.ajaxsettings ,设置请求的参数
ajaxsetup: function (settings) {
jquery.extend(jquery.ajaxsettings, settings);
},
ajax: function (origsettings) { // 实际的 ajax 函数
var s = jquery.extend(true, {}, jquery.ajaxsettings, origsettings);
// 创建 xhr 对象
xhr = s.xhr();
// 回调函数
var onreadystatechange = xhr.onreadystatechange = function (istimeout) {
if (xhr.readystate === 4) {
if (xhr.status == 200) {
s.success.call(origsettings, xhr.responsetext);
}
}
};
// 设置请求参数
xhr.open(s.type, s.url);
// send the data 发出请求
xhr.send(s.data);
// return xmlhttprequest to allow aborting the request etc.
return xhr;
},
// 使用 get 方式发出 ajax 请求的方法
get: function (url, data, callback, type) {
// shift arguments if data argument was omited
if (jquery.isfunction(data)) {
type = type || callback;
callback = data;
data = null;
}
return jquery.ajax({
type: get,
url: url,
data: data,
success: callback,
datatype: type
});
}
}); // #6922
// 扩展 jquery 对象,增加 load 方法
jquery.fn.extend(
{
load: function (url) {
var self = this;
jquery.get(url, function (data) {
self.each(function () {
this.innerhtml = data;
}
)
}
)
}
}
)
在页面中,可以如下使用。
复制代码 代码如下:
其它类似信息

推荐信息