java jsonp 跨域 Uncaught SyntaxError: Unexpected token :

ajax在跨域请求的是,发生跨域问题,因此想到了jsonp来处理,

--------------------------------------------代码修改前------------------------------------------

但是随之而来又来了新的问题。JS代码如下:

$.ajax({
    type: "get",
    url: "http://www.zhiqi17.com/pay/wxpay/getPayInWeChat/" + getUrlParam('orderId'),
    contentType: "application/json; charset=utf-8",
    dataType: 'jsonp',
    data: {
        openId: res.data
    },
    async: false,
    success: function(obj) {
        console.log(obj);
    }
});

后台java代码如下:

@RequestMapping(value = "/test", method = RequestMethod.GET)
	public @ResponseBody Object getPayInWeChat(HttpServletRequest request){
		Map returnMap=new HashMap();
		returnMap.put("a", "123");
		returnMap.put("b", "4456");
		return JSONObject.toJSONString(returnMap);
	}
经调用浏览器回报如下错误:

Console中:

java jsonp 跨域 Uncaught SyntaxError: Unexpected token :_第1张图片

Network中:

java jsonp 跨域 Uncaught SyntaxError: Unexpected token :_第2张图片

返回结果中Response中拿到了后台返回的数据。

-------------------------------------------------代码修改后----------------------------------------------------

js代码:

$.ajax({
    type: "get",
    url: "http://abc.com/test",
    contentType: "application/json; charset=utf-8",
    dataType: 'jsonp',
    jsonp: 'callback',//自定义
    jsonpClaaback: "success_jsonpCallback",//用户定义的callback函数,没有定义的话会jQuery会自动生成以jQuery开头的函数 
    data: {
        openId: res.data
    },
    async: false,
    success: function(obj) {
        console.log(obj);
    }
});
以上代码标红为修改的代码。

java 代码:

@RequestMapping(value = "/test", method = RequestMethod.GET)
	public @ResponseBody Object getPayInWeChat(HttpServletRequest request){
		Map returnMap=new HashMap();
		returnMap.put("a", "123");
		returnMap.put("b", "4456");
		String callback = request.getParameter("callback"); //不指定函数名默认 callback
		return callback+ "(" + JSONObject.toJSONString(returnMap) + ")";
	}

这样就完美解决jsonp的问题啦。




你可能感兴趣的:(js)