我无法通过servlet响应获取Json文本.servlet代码正常工作。我的Ajax代码有问题。代码......
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");
}
}
}
答案 0 :(得分:1)
我有同样的问题,但我更改了启动部分&在我的情况下它的工作。
阻止代码:
var json = eval('(' + xmlhttp.responseText +')');
工作代码:
var json = "";
json = eval('(' + xmlhttp.responseText +')');
此致 Shyam Miyatra
答案 1 :(得分:0)
我无法帮助JSP,但希望这个例子对JavaScript部分有所帮助:
<script>
...
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
// json now contains an array of objects, eg:
//
// [
// {
// "productNumber" : "001",
// "productType" : "User Manual",
// "funcDesignation": "Operator"
// }
// ]
// grab the first (and only) object in the array
var firstRecord = json[0];
// update the UI by selecting DOM elements and rewriting their contents
document.getElementById('product-number').innerHTML =
firstRecord.productNumber;
document.getElementById('product-type').innerHTML =
firstRecord.productType;
document.getElementById('func-designation').innerHTML =
firstRecord.funcDesignation;
} else {
alert("Error during AJAX call. Please try again");
}
}
}
</script>
...
<h4>Product</h4>
<div>Number: <span id="product-number"></span></div>
<div>Type: <span id="product-type"></span></div>
<div>Function: <span id="func-designation"></span></div>
...
PS - 你可能想要考虑jQuery,MooTools或其他现代JavaScript框架;他们更容易进行AJAX调用并使用DOM。