ajax跨域请求--jsonp实例
ajax请求代码:
@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.jsonp的数据格式是:jsonpCallback+"("+resultJson.toString()+")"
举个例子:
jsonpCallback({
"code": "aaa",
"price": 1780,
"tickets": 5
});
相关推荐
fengchao000 2020-06-17
adonislu 2020-05-16
zmosquito 2020-05-10
adonislu 2020-05-10
somebodyoneday 2020-04-22
fengchao000 2020-04-22
fengchao000 2020-04-11
Richardxx 2020-03-07
somebodyoneday 2020-03-06
fengchao000 2020-03-05
somebodyoneday 2020-02-16
xiaouncle 2020-02-13
baijinswpu 2020-01-29
fengchao000 2020-01-10
fengchao000 2019-12-25
newthon 2019-12-23
somebodyoneday 2013-07-11