<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script>
window.onload = function() {
/*加载一个script*/
var getScript=function(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// 跨瀏覽器處理 script 下載完成後的事件
script.onload = script.onreadystatechange = function() {
if (!this.readyState ||
this.readyState === "loaded" ||
this.readyState === "complete") {
this.onload = this.onreadystatechange = null;
document.getElementsByTagName('head')[0]
.removeChild(this);
callback();
}
};
document.getElementsByTagName('head')[0]
.appendChild(script);
}
/*设置参数*/
var param=function(obj) {
var pairs = [];
for(var name in obj) {
var pair = encodeURIComponent(name) + '=' +
encodeURIComponent(obj[name]);
pairs.push(pair.replace('/%20/g', '+'));
}
return pairs.join('&');
};
var jsonp=function(option, callbackName) {
// 沒有url或伺服端要求的callbackName就結束
if(!option.url || !callbackName) {
return;
}
var data = option.data || {};
// 建立暫時的函式
data[callbackName] = 'XD' + new Date().getTime();
window[data[callbackName]] = function(json) {
option.callback(json);
};
var url = option.url + '?' + param(data);
// 取得 script 檔案
getScript(url, function() {
// script 下載並執行完後移除暫時的函式
window[data[callbackName]] = undefined;
try {
delete window[data[callbackName]];
}
catch(e) {}
});
};
document.getElementById('test').onclick = function() {
jsonp({
url : 'http://caterpillar.onlyfun.net/Gossip/' +
'JavaScript/samples/JSONP-1.php',
data : {
id : document.getElementById('id').value,
},
callback : function(person) {
document.getElementById('result').innerHTML =
person.name + ',' + person.age;
}
}, 'jsoncallback');
};
}
</script>
<body>
<div>
<input type="text" name="name" id="id"><br>
<input type="button" id="test">
<div id="result"></div>
</div>
</body>
<script></script>
</html>
jsop的原理
我们可以通过使用 html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象