使用jQuery和jsonp解決js跨域問題
客戶端系統js代碼:<script type="text/javascript">
function test(a){
alert(a.name);
return a;
}
$.ajax({
url:'http://ip:8090/mobile/test.json?method=test',
type:'POST', //GET
async:true, //或false,是否異步
data:{
// name:'yang',age:25
},
timeout:5000, //超時時間
dataType:'jsonp', //返回的數據格式:json/xml/html/script/jsonp/text
beforeSend:function(xhr){
},
success:function(data,textStatus,jqXHR){
},
error:function(xhr,textStatus){
},
complete:function(){
}
})
</script>
服務端系統代碼:
服務端系統代碼:
test({name:'yang',age:25});
客戶端訪問跨域系統時,傳遞客戶端需要執行的方法名,服務端在查詢出數據后,使用傳遞的方法名封裝成js方法的執行返回,客戶端程序就直接執行此方法。
springmvc后臺例子,返回jsonp數據代碼
客戶端訪問跨域系統時,傳遞客戶端需要執行的方法名,服務端在查詢出數據后,使用傳遞的方法名封裝成js方法的執行返回,客戶端程序就直接執行此方法。
springmvc后臺例子,返回jsonp數據代碼
//第一種字符串返回jsonp格式數據
@RequestMapping(value="/get/{method}",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@ResponseBody
public String getUser(@PathVariable String method) {
User user = userService.selectByPrimaryKey(1);
Gson gson = new Gson();
String userJson = gson.toJson(user);
return method+"("+userJson+")";
}
//第二種對象返回jsonp格式數據
spring版本4.1以上
spring版本4.1以上
@RequestMapping("/gett/{method}")
@ResponseBody
public Object gett(@PathVariable String method) {
User user = userService.selectByPrimaryKey(1);
MappingJacksonValue mjv = new MappingJacksonValue(user);
mjv.setJsonpFunction(method);
return mjv;
}