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<String,String> returnMap=new HashMap<String, String>();
		returnMap.put("a", "123");
		returnMap.put("b", "4456");
		return JSONObject.toJSONString(returnMap);
	}
經調用瀏覽器回報如下錯誤:

Console中:

Network中:


返回結果中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<String,String> returnMap=new HashMap<String, String>();
		returnMap.put("a", "123");
		returnMap.put("b", "4456");
		String callback = request.getParameter("callback"); //不指定函數名默認 callback
		return callback+ "(" + JSONObject.toJSONString(returnMap) + ")";
	}

這樣就完美解決jsonp的問題啦。




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