ajax跨域請求,頁面和java服務端的寫法


方法一(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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM