我無法通過servlet響應來獲取Json文本。servlet代碼正在工作。我的Ajax代碼有問題。代碼...通過ajax檢索Json文本的問題
var json = eval('(' + xmlhttp.responseText +')');
...沒有返回任何東西。有沒有需要這樣做的罐子?以下是我的代碼:
//Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
List result = new ArrayList();
result.add(new SearchResponse("001", "User Manual", "Operator"));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(result));
}
在我的Ajax中,我正在編寫下面的代碼來獲取它。
function ajaxFunction() {
alert("function called...");
if (xmlhttp) {
alert(AJAX_SERVLET);
xmlhttp.open("GET", AJAX_SERVLET, true); //AJAX_SERVLET has the servlet path
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
alert(xmlhttp.readyState);
if (xmlhttp.readyState == 4) {
alert(xmlhttp.status);
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
alert(json);
var json = eval('(' + xmlhttp.responseText +')');
request.setAttribute("output",json);
} else {
alert("Error during AJAX call. Please try again");
}
}
}
如果你只是使用'的eval(xmlhttp.responseText)會發生什麼'甚至跳過EVAL部分?你有什麼數據嗎? – psema4 2011-06-09 16:32:47
你可以發佈你的'responseText',這樣我們可以看到它是否有效?您的警報中哪些 - 如果有的話 - 觸發? – ajm 2011-06-09 16:46:55