JSP+JQuery+Ajax 使用JSON方式取得Server-Side網頁回傳值
查網路上查到JSON是一個使用key-value架構的資料格式, 但我只要在dataType指定為"json", JQuery就會出錯, 我想可能是我搞錯 JQuery Ajax json的使用方式了吧。以下為我測試出來的程式碼, 記錄一下。
<Client-Side>
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<title>jquery client submit insert data</title>
<script src="jquery-1.11.0.js" type="text/javascript"></script>
</head>
<body>
<div id="apply">
<table>
<tr>
<td style="width:80px;">UserId</td>
<td><input type="text" id="txtUserId" name="txtUserId" /></td>
</tr>
<tr>
<td style="width:80px;">UserName</td>
<td><input type="text" id="txtUserName" name="txtUserName" /></td>
</tr>
</table>
<input type="button" id="btnSumit" name="btnSubmit" value="submit" />
</div>
<div id="result"></div>
<div id="log"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#txtUserId").val("your_id");
$("#txtUserName").val("your_name");
});
$("#btnSumit").click(function(e){
alert("submit!");
$.ajax({
type: "POST",
url: "userData.jsp",
data: {type: "i", txtUserId: $("#txtUserId").val(), txtUserName: $("#txtUserName").val()},
//dataType: "text",
//dataType: "html",
//dataType: "json",
cache: false,
success: function(response){
var data = $.parseJSON(response);
alert(data.exeStatus);
alert(data.msg);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError.Error);
}
});
});
</script>
<Server-Side>
<%@page import="org.json.JSONObject"%>
<%
JSONObject json = new JSONObject();
json.put("exeStatus", "Y");
json.put("msg", "OKOK");
out.println(json);
%>
因為有使用到JSONObject的lib, 所以要先去下載jar檔放在WEB-INF\lib, 並在Eclipse中加入jar就可以使用了。
JSONObject download : http://example.javamonday.com/Code/Jar/j/Downloadjsonjavajar.htm
Hello 感謝你 看完這篇文章我更了解Ajax 搭配JSP的用法
回覆刪除關於dataType指定為"json", JQuery就會出錯的問題
我發現是因為 只要把dataType指定為json後
response會直接變為處理後的物件
所以不需要var data = $.parseJSON(response);這一行
直接打
alert(response.exeStatus);
alert(response.msg);
就會印出正確的結果!!
原來是這樣子, 謝謝你。
刪除