1. 程式人生 > >使用jQuery傳送POST,Ajax請求返回JSON格式資料

使用jQuery傳送POST,Ajax請求返回JSON格式資料

問題:使用jQuery POST提交資料到PHP檔案, PHP返回的json_encode後的陣列資料,但jQuery接收到的資料不能解析為JSON物件,而是字串{"code":-1,"msg":"123","data":[]}jQuery get() 和 post() 方法用於通過 HTTP GET 或 POST 請求從伺服器請求資料。jQuery $.get() 方法$.get() 方法通過 HTTP GET 請求從伺服器上請求資料,在URL地址上可以看到傳遞的引數,一般用於傳遞少量資料。
語法: $.get(URL,callback);詳細語法:$(selector).get(url, data, success(response,status,xhr),dataType)
jQuery $.post() 方法$.post() 方法通過 HTTP POST 請求從伺服器上請求資料,在URL地址上不可以看到傳遞的引數,一般用於傳遞大量資料。
語法:$.post(URL,data,callback);詳細語法: jQuery.post(url,data,success(data, textStatus,jqXHR),dataType)檢視$.post()詳細的語法:jQuery.post(url,data,success(data, textStatus,jqXHR),dataType)你會發現,最後邊有個引數 dataType,這個就是問題所在。這個dataType是可選引數,它規定預期的伺服器響應的資料型別。預設執行智慧判斷(xml、json、script 或html)。
詳細說明該函式是簡寫的 Ajax 函式,等價於:$.ajax({  type: 'POST',  url: url,  data: data,  success: success,  dataType: dataType});解決:$.post() 加上最後邊的一個可選引數 dataType 為“json”型別示例:獲得 test.php 頁面返回的 json 格式的內容:$.post("test.php", { "func": "getNameAndTime" },function(data){alert(data.name); // Johnconsole.log(data.time); // 2pm
},"json");示例:獲得 test.php 頁面的內容,並存儲為 XMLHttpResponse 物件,並通過 process() 這個JavaScript 函式進行處理:$.post("test.php", { name: "John", time: "2pm" },function(data){process(data);},"xml");
Struts2中對於後臺向前端返回JSON格式資料一般使用以下方式:
<span style="font-size:18px;">	public void writeJson2Resp(String json) throws IOException {
		HttpServletResponse resp = ServletActionContext.getResponse();
		resp.setCharacterEncoding("gbk");
		resp.setContentType("text/html;charset=gbk");  //這一句沒加入會導致亂碼
		PrintWriter out = resp.getWriter();
		out.write(json);
		out.flush();
		out.close();
	}</span>

在 BaseAction 實現該方法,那麼其他的 Action  只要繼承了改類,就可以使用該方法向前臺頁面返回JSON格式資料
參考連結:jQuery ajax 參考手冊http://www.w3school.com.cn/jquery/jquery_ref_ajax.aspHTTP 方法:GET 對比 POSThttp://www.w3school.com.cn/tags/html_ref_httpmethods.aspjQuery ajax - post() 方法:http://www.w3school.com.cn/jquery/ajax_post.aspjQuery ajax - get() 方法http://www.w3school.com.cn/jquery/ajax_get.asp

關注公眾號,分享乾貨,討論技術