jsonP插件的服装var url = 'http://localhost:3000/data/swiper';
(function(root){
jsonp = function(url,data,jsonpcallback,callback){
var cbName = 'cb'+ jsonp.count;
var fnName = jsonpcallback + '=' + cbName;
root[cbName] = function(res){
callback(res);
}
var script = document.createElement('script');
var data = tools.parse(data);
url = tools.hasSearch(url,fnName);
url = tools.hasSearch(url,data);
script.src = url;
document.body.appendChild(script);
}
var tools = {
parse : function(data){
if(!data){return ''}
if(typeof data == 'string'){
return data;
}
var arr = [];
for(var key in data){
arr.push(encodeURIComponent(key)+'='+encodeURIComponent(data[key]));
}
return arr.join('&');
},
hasSearch : function(url,str){
if(!str){return url};
if(typeof str !== 'string'){return url}
return url + (/\?/.test(url) ? '&' : '?') + str;
}
}
jsonp.count = 0;
root.jsonp = jsonp
})(window)
调用方式
var url = 'http://localhost:3000/data/swiper';
var data = {a:1};
jsonp(url,data,'callback',function(res){
console.log(res);
});
服务点node接口的实现
let callback = req.query.callback;
const sendData = {
status: 0,
msg: "",
data: "",
}
if(imgNames) {
sendData.status = 1;
sendData.msg = "success";
sendData.data = imgNames;
}else {
sendData.msg = "error";
}
let json = JSON.stringify(sendData);
res.send(callback + '(' + json + ')');