ajax请求代码:
//区域事件选择配送点 function changeDistrict(value){ if(value == 0){ $('#transport_node').empty(); $('#transport_node').append('<option value="0">请选择</option>'); return; } $('#transport_node').empty(); $('#transport_node').append('<option value="0">载入中...</option>'); $.ajax({ type: 'GET', url: "http://192.168.33.114:8080/UIDTraceAdmin/transportnode/pagelist/jsonp?callbackFunction=jsonpCallback", async: false, dataType: "jsonp", jsonp: "jsonpCallback",//传递给请求处理程序或页面的。用以获得jsonp回调函数名的參数名(一般默觉得:callback) success: function(o){}, timeout:3000 }); } //注意:跨域服务端响应返回后调用此函数 function jsonpCallback(result) { ....//详细代码省略 }
要点:
1.url中的请求參数callbackFunction=jsonpCallback这是server响应返回后调用的javascript方法的名称
2.dataType要为jsonp
跨域server处理代码:
@RequestMapping("/pagelist/jsonp") public void pagelist(@ModelAttribute TransportNode node,HttpServletRequest httpReq, HttpSession session,HttpServletResponse response) { //返回头部设置 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-type", "application/x-javascript;charset=utf-8"); response.setDateHeader("Expires", 0); String jsonpCallback = httpReq.getParameter("callbackFunction");//jsonp回调函数名 JSONObject resultJson = new JSONObject(); PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e1) { e1.printStackTrace(); } try { node.setRowStart((node.getPage() - 1) * node.getRows() + 1); node.setRowEnd(node.getPage() * node.getRows()); resultJson.put("transportList", JsonUtils.toJSONList(business.getList(node))); resultJson.put("success", true); System.out.println(resultJson.toString()); out.println(jsonpCallback+"("+resultJson.toString()+")");//返回jsonp格式数据 out.flush(); out.close(); } catch (Exception e) { LogWriter.log("/pagelist/jsonp",e); try { resultJson.put("success", false); } catch (JSONException e1) { e1.printStackTrace(); } out.println(jsonpCallback+"("+resultJson.toString()+")");//返回jsonp格式数据 out.flush(); out.close(); }
注意要点:
1.设置响应报文头,response.setHeader("Content-type", "application/x-javascript;charset=utf-8");,消除了"Resource interpreted as Script but transferred with MIME type text/plain",同一时候要依据自己的编码格式设置正确的编码;
2.跨域server响应给给client的数据为:要调用的javascript函数名称(json格式的数据),在这个样例中,比方响应返回了例如以下的数据
jsonpCallback({
"code": "aaa",
"price": 1780,
"tickets": 5
});
client接收到数据后。调用
function jsonpCallback(result) { ...}
{ "code": "aaa","price": 1780,"tickets": 5}会自己主动解析成result。
要訪问数据中的“code”的值,在函数体里写result.code就可以。