文章目录
前端:
<!DOCTYPE html>
<html>
<head>
<title>手写jsonp</title>
</head>
<body>
<p>
jsonp的原理与实现 https://segmentfault.com/a/1190000007665361
</p>
<script type="text/javascript">
function jsonp(req) {
var script = document.createElement('script');
var url = req.url + '?callback=' + req.callback.name;
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function getscript(res) {
console.log(res)
}
jsonp({
url: 'http://localhost:3000',
callback: getscript
});
/*上面jsonp的实现有些不足:
1.我们传递的回调必须是一个全局方法,我们都知道要尽量减少全局的方法。
2.需要加入一些参数校验,确保接口可以正常执行。
*/
(function (global) {
var id = 0,
container = document.getElementsByTagName("head")[0];
function jsonp1(options) {
if (!options || !options.url) return;
var scriptNode = document.createElement("script"),
data = options.data || {},
url = options.url,
callback = options.callback,
fnName = "jsonp" + id++;
// 添加回调函数
data["callback"] = fnName;
// 拼接url
var params = [];
for (var key in data) {
params.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
url = url.indexOf("?") > 0 ? (url + "&") : (url + "?");
url += params.join("&");
scriptNode.src = url;
// 传递的是一个匿名的回调函数,要执行的话,暴露为一个全局方法
global[fnName] = function (ret) {
callback && callback(ret);
container.removeChild(scriptNode);
delete global[fnName];
}
// 出错处理
scriptNode.onerror = function () {
callback && callback({ error: "error" });
container.removeChild(scriptNode);
global[fnName] && delete global[fnName];
}
scriptNode.type = "text/javascript";
container.appendChild(scriptNode)
}
global.jsonp1 = jsonp1;
})(this);
jsonp1({
url: "http://localhost:3000",
data: { id: 1 },
callback: function (ret) {
console.log(ret);
}
});
</script>
</body>
</html>
后台:
var http = require('http');
var urllib = require('url');
var port = 3000;
var data = {'data':'world'};
http.createServer(function(req,res){
var params = urllib.parse(req.url,true);
if(params.query.callback){
console.log(params.query.callback);
//jsonp
var str = params.query.callback + '(' + JSON.stringify(data) + ')';
res.end(str);
} else {
res.end();
}
}).listen(port,function(){
console.log('jsonp server is on');
});