不多说据体看源码
js部分:
(function(window) {
window._ = {
/********************是否为json**************************/
/*
*参数json:可以是obj也可以是string
*/
isJSON : function(json){
//obj的判断
if(typeof(json) == "object" && Object.prototype.toString.call(json).toLowerCase() == "[object object]" && !json.length) {
return true;
}
//string的判断
if(typeof(json) == "string") {
try {
var obj = JSON.parse(json);
if(typeof obj == 'object' && obj ){
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
//不是ojb json也不是string json
return false;
}
/********************是否为json**************************/
/********************jsonp**************************/
/*匿名或不匿名回调函数*/
, fn : null ,
/*临时节点*/
temp : null ,
/*
*config参数列表:url、data、callBack
*url:请求地址
*data:请求参数列表可以是:json对象、json字符串、字符串请求参数串
*callBack:回调函数,可以是匿名或不匿名函数
*/
jsonp : function(config) {
//匿名或不匿名回调函数
this.fn = config.callBack;
//参数列表数组
var arr = new Array();
//是json对象或json字符串
if(this.isJSON(config.data)) {
//json字符串转成json对象
if(typeof(config.data) == "string") {
config.data = JSON.parse(config.data);
}
//json转换成字符串数组
for(var key in config.data) {
arr.push(key + "=" + config.data[key]);
}
} else if(typeof(config.data) == "string") {
//string请求参数串
arr.push(config.data);
}
//避免请求被缓存
arr.push("time=" + new Date().getTime());
//创建临时节点
this.temp = document.createElement("script");
//利用script标签src属性的特性进行跨域
this.temp.src = config.url + "?callBack=_.callBack&" + arr.join("&");
document.body.appendChild(this.temp);
} ,
/*回调函数*/
callBack : function(data) {
//回调
this.fn && this.fn(data);
//删除临时节点
this.temp.parentNode.removeChild(this.temp);
}
/********************jsonp**************************/
}
})(window);
服务端测试部分:
@RequestMapping("/jsonp")
public void jsonp(HttpServletResponse response,String callBack,String username,String password , String time) throws IOException {
response.setContentType("text/javascript");
String cb = callBack + "({'username':'" + username + "','password':'" + password + "','result':'200'});";
Writer out = response.getWriter();
out.write(cb);
System.out.println(time);
}
HTML测试部分:
var url = "http://localhost:8080/jsonp";
var json = {"username":"zhangshang","password":"123456abc"};
_.jsonp({
url : url ,
data : json ,
callBack : function(data) {
for(var key in data) {
console.log(key + " : " + data[key]);
}
}
});
利用script的src属性实现jsonp跨域
最新推荐文章于 2022-11-02 17:46:46 发布