方法一(jsonp):javascript
頁面ajax請求的寫法:java
$.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服務端寫法:ajax
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(); } }
方法二:json
在服務端設置response.setHeader("Access-Control-Allow-Origin", "*");便可。跨域
Access-Control-Allow-Origin:* 表示容許任何域名跨域訪問async
若是須要指定某域名才容許跨域訪問,只需把Access-Control-Allow-Origin:*改成Access-Control-Allow-Origin:容許的域名
jsonp
例如:response.setHeader("Access-Control-Allow-Origin", "http://www.client.com");url