方法一(jsonp):
頁面ajax請求的寫法:
$.ajax({ type : "get", async : false, cache : false, url : "http://localhost:8081/a/b", data : { produ_id: 111, sub_id: 0, produ_quantity: 1, produ_price: 0.0 }, dataType : "jsonp", jsonp: "jsonpCallback", success : function(data) { var d = data; alert(d); }, error : function() { alert('fail'); } });
java服務端寫法:
public void ajaxRequest(Params params) { HttpServletRequest request = ; HttpServletResponse response = ; response.setContentType("text/plain"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0);
response.setCharacterEncoding("UTF-8"); Map<String, String> map = new HashMap<String, String>(); map.put("result", "content"); PrintWriter out = null; try { out = response.getWriter(); String jsonString = JSONObject.toJSONString(map);//隨便使用哪個JSONObject都可以,這里只是轉為json格式的字符串就行 String jsonpCallback = request.getParameter("jsonpCallback");// 客戶端請求參數 out.println(jsonpCallback + "(" + jsonString + ")");// 返回jsonp格式數據 } catch (IOException e) { e.printStackTrace(); } finally{ out.flush(); out.close(); } }
方法二:
在服務端設置response.setHeader("Access-Control-Allow-Origin", "*");即可。
Access-Control-Allow-Origin:* 表示允許任何域名跨域訪問
如果需要指定某域名才允許跨域訪問,只需把Access-Control-Allow-Origin:*改為Access-Control-Allow-Origin:允許的域名
例如:response.setHeader("Access-Control-Allow-Origin", "http://www.client.com");