ajax & jsonp & img

时间:2021-12-31 17:37:55

ajax 是一种请求服务器的方式,核心是XMLHttpRequest对象;

优点是无需刷新页面,

缺点是不能跨域请求。

/*
* Ajax direacted by Zakas
*
* Ajax.get("url?p=value", function (data) { // handle data }, false);
*
* Ajax.post("url",{
* data : "p=value&id=001",
* callback : function (data) { // handle data },
* async : false
* });
*
*/
var Ajax = (function () { "use strict"; var ajax = { // 惰性载入函数
createXHR: (function () { if (window.XMLHttpRequest) { // 不论new多少次XHR,if只需判断一次
return function () {
return new XMLHttpRequest();
};
} else { // only for ie 6 hack
return function () {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
}()), get: function (url, callback, async) { var XHR = this.createXHR(); // 默认异步请求
if (async !== false) {
async = true;
} if (async) { // 异步请求
XHR.onreadystatechange = function () { if (XHR.readyState === 4 && XHR.status === 200) {
callback(XHR.responseText); // 销毁不用的对象,因为每次ajax请求都会创建一个新的XHR
XHR = null;
}
} XHR.open("get", url, true);
XHR.send(null);
} else { // 同步请求,返回结果前停止解析上下文
XHR.open("get", url, false);
XHR.send(null);
callback(XHR.responseText);
XHR = null;
}
}, post: function (url, option) { var XHR = this.createXHR();
data = option.data,
callback = option.callback,
async = option.async; if (async !== false) {
async = true;
} if (async) { XHR.onreadystatechange = function () { if (XHR.readyState === 4 && XHR.status === 200) {
callback(XHR.responseText);
XHR = null;
}
} XHR.open("post", url, true);
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHR.send(data);
} else {
XHR.open("post", url, false);
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHR.send(data);
callback(XHR.responseText);
XHR = null;
}
}
}; return ajax;
}());

页面中常见的能够跨域进行http请求的有两个标签:<script src=""></script> && <img src="" />

jsonp(JSON with padding)的原理就是<script src=""></script>

// jsonp 是一种可以通过约定进行自定义回调函数的跨域脚本

// 预先定义回调函数
function handleResponse (data) {
// data is a json from remote-source-domain, now deal it in this.
} var script = document.createElement("script");
script.src = "http://remote-source-domain?callback=handleResponse"; // 远程脚本中的数据:handleResponse({data: "json", time: "2014-06-11"});
document.getElementsByTagName("head")[0].appendChild(script); // 当脚本被加载到文档中时,handleResponse函数立即执行

IMG

// 当img对象被赋予src属性时立即发生http请求
var img = new Image();
img.src = "http://remote-source-domain"; // 此时发生了http请求,远程资源被加载到本地 // 图片的预加载
var imgArr = ["0.jpg", "1.jpg", "2.jpg"],
len = imgArr.length,
i; for (i = 0; i < len; i++) {
img.src = imgArr[i];
}