自己动手写jsonp
in Web前端 on javascript web 前端 - Hits()
jsonp是解决跨域调用的一种方法,主要是通过script标签允许跨域的原理来实现。
下面就是示例代码:
var head = document.getElementsByTagName("head")[0];
var j = document.createElement("script");
j.type = "text/javascript";
if (c){
var id='tpc'+new Date().getTime();
src += '&jsonpid='+id;
//the response should call the function passed by jsonpid
window[id] = function(r){c(r);window[id]=null;};
}
j.onload = j.onreadystatechange = function() {
if ((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
//ie hack
j.onload = j.onreadystatechange = null;
if (head && j.parentNode) {
head.removeChild(j);
}
}
}
j.src = src + '&tmp=' + new Date().getTime();
head.appendChild(j);
需要注意的问题是:
IE下onload事件触发不了,但是有onreadystatechange事件,
script标签设置一次src后,再改动它的src是没有效果的,所以必须每次创建,然后删除。
上面的例子还需要服务端返回的script内容调用传入的函数名来达到传递参数的效果。
还没有想到失败事件怎样实现?

