之前写过一篇JSONP实现原理的文章,见这里,偶尔翻出来看看总觉得写的有些乱,今天整理一下:
之所以采用这种方式,完全是为了跨域的需要,一般情况下后台只需要输出一个json数据即可,现在为了跨域,也需要后台来配合完成,即前端传递一个特定的参数,后台接收到此参数后将原本的json数据按照参数的值输出类似callback1309065300052({"name":"jack","age":"20"}) 的格式,见http://api.zhui.cn/content/ZIDList.json?jsoncallback=callback1309065300052
下面正式开始:
//getJSON
function getJSON(url, func){
if (!document.getElementById) {
return false;
}
if (document.getElementById("jsonscript")) {
var oldscript = document.getElementsByTagName("script");
for (var i = 0; i < oldscript.length; i++) {
if (oldscript[i].getAttribute("src") == url) {
oldscript.parentNode.removeChild(oldscript);
}
}
}
var script = document.createElement("script");
var callback = 'callback'+ (+new Date());
url+="?jsoncallback="+callback;
script.setAttribute("src", url);
window[callback]=func;
script.setAttribute("id", "jsonscript");
document.getElementsByTagName("head")[0].appendChild(script);
}
调用:
getJSON("http://api.zhui.cn/content/ZIDList.json",parseDZList);
function parseDZList(json){
var show = document.getElementById("show");
var Status = json.StatusInfo.Status;
var items = json.Items;
for (var i = 0; i < items.length; i++) {
//...
}
}
Comments(0)