我想解析JSP內的AJAX響應中的JSON內容。響應是對象列表。我無法讀取單個變量。請查找附加的代碼以供參考。解析AJAX響應中的JSON內容
JsonTest.jsp
<html>
<head>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
</head>
<body>
COMPONENT CODE : <input name="PartCode" id="PartNo" type="text" />
<br><br>
COMPONENT DESCRIPTION : <input name="desc" id ="Description" value=''>
<br><br>
QUANTITY : <input name="qty" id="Quantity" type="text" value=""/>
<script type="text/javascript">
$('#PartNo').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
varPartCode = $('#PartNo').val();
$.ajax({
type: "Post",
url: "submit",
data: "PartCode="+varPartCode,
headers: {Accept : "application/json;charset=utf-8","Content-Type":"application/json;charset=utf-8"},
success: function(json){
var rep = JSON.parse(json);
alert(rep.name);
}
});
}
});
</script>
</body>
</html>
TestBean.java
package test.json.MyJsonCode;
public class TestBean {
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
code1.java
package test.json.MyJsonCode;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Code1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
List<TestBean> testList = new ArrayList<TestBean>();
TestBean test = new TestBean();
test.setDesc("description1");
test.setName("name1");
testList.add(test);
TestBean test2 = new TestBean();
test2.setDesc("description2");
test2.setName("name2");
testList.add(test2);
Gson gson = new Gson();
System.out.println("inside code1 class");
String jsonList = gson.toJson(testList);
System.out.println("json data"+jsonList);
response.getWriter().write(jsonList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
警報未彈出的名字這value.is正確的方式解析?還是代碼中需要的任何更正?提前請求您的支持和感謝。
你不需要解析響應數據對象,jQuery的已經做到了 – baao
這不是真正的entirly @baao但是,如果你發送的正確HTPT頭並設置[dataType:json](http://api.jquery.com/jquery.ajax/),那麼你應該得到一個對象不是一個字符串 – Liam
你應該使用contentType重載真正設置內容類型,而不是頭部重載FYI – Liam