java学习

java学习

 

使用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数据代码
//第一种字符串返回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以上
@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;
 
}

posted on 2017-02-22 15:55 杨军威 阅读(192) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜