ajax中jsonp跨域,回调成功但是进入error方法中

首先你要确定什么是跨域

https://blog.csdn.net/u014727260/article/details/72793459

附上前端代码

    var data = {
        "username":"123",
        "password":"456"
    }
    $.ajax({
        url: "http://localhost:9091/xxx/saveInfo",
        type: "GET",
        dataType: "jsonp",
        jsonp: "callback",
        jsonpCallback:"message" ,
        data: data,
        success:function(data){
        console.log(data.name);
        },
        error:function(data){
        console.log(data);
        }
    })

附上后台代码

    @RequestMapping(value = "/saveInfo",method = RequestMethod.GET)
    @ResponseBody
    public String saveInfo(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"---------"+password);

        Map<String, String> map = new HashMap();
        map.put("name", "124");
        return JSON.toJSONString(map);
    }

这是刚开始写的api,但是无论怎么调用,在前端接受回调数据的时候都会进入error()当中。

 

后端代码稍作修改之后:

    @RequestMapping(value = "/saveInfo",method = RequestMethod.GET)
    @ResponseBody
    public String saveInfo(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"---------"+password);

        Map<String, String> map = new HashMap();
        map.put("name", "124");
        String callback = request.getParameter("callback");
        String result = callback + "(" + JSON.toJSONString(map) + ")";
        return result;
    }

 这里需要将回调函数的名字作为方法名,而调用接口返回的内容作为参数的方式进行拼接返回。

这里注意,使用dataType使用jsonp,返回数据的格式,是json{"name":"123"}还是text{"hello world!"}由你自己在后台返回数据的时候自行定义。

当选择dataType为jsonp的时候,type只能为GET,这也是jsonp跨域请求为什么不安全,所以使用jsonp来实现跨域需要谨慎。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章