不多说据体看源码
js部分:
(function(window) {
window._ = {
isJSON : function(json){
if(typeof(json) == "object" && Object.prototype.toString.call(json).toLowerCase() == "[object object]" && !json.length) {
return true;
}
if(typeof(json) == "string") {
try {
var obj = JSON.parse(json);
if(typeof obj == 'object' && obj ){
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
return false;
}
, fn : null ,
temp : null ,
jsonp : function(config) {
this.fn = config.callBack;
var arr = new Array();
if(this.isJSON(config.data)) {
if(typeof(config.data) == "string") {
config.data = JSON.parse(config.data);
}
for(var key in config.data) {
arr.push(key + "=" + config.data[key]);
}
} else if(typeof(config.data) == "string") {
arr.push(config.data);
}
arr.push("time=" + new Date().getTime());
this.temp = document.createElement("script");
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);
}
}
})(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]);
}
}
});