【发布时间】:2013-08-08 07:54:15
【问题描述】:
我正在调用一个 servlet 从数据库中获取对象列表,并且该列表作为 json 从 servlet 返回。相同的 json 响应将显示在 jsp 表中,如下所示。
Servlet 代码:
String json = new Gson().toJson(resultList);
response.setContentType("application/json"); //here i have the data and i came to know by debugging
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
jquery 代码:
$.ajax({
type: "GET",
url: "./dataFetchController",
success: function(responseJson) {
console.log(responseJson); //it is not printing any result on firebug console
var master = $(this).parents("table.myTable");
$.each(responseJson, function(index, contact) { // Iterate over the JSON array.
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone();
prot.attr("class", "");
prot.find("#myName").attr("value", contact.name);
prot.find("#myLastName").attr("value", contact.lastName);
//master.find("tbody").append(prot);
jQuery('table.myTable tr:last').before(prot);
});
},
error: function(ob,errStr) {
$('#contactForm #formProgress').html('');
$('#contactForm #formProgress').html('<img src="./public/images/error.png" /> <span style="color:red">Save is not successful. Try Again.</span>');
}
});
我没有得到任何 json 结果。我尝试使用控制台打印它但没有结果,但在 servlet 中它有从数据库返回的数据并使用调试进行验证。我在这里有什么遗漏吗?
谢谢!
【问题讨论】:
-
您确定它正在进入
success块吗? -
是的..它正在进入成功块..我通过保持警报来验证。但数据不来..
-
@Gaara,有没有其他方法可以从 servlet 获取对象列表作为对 ajax 调用的响应?
-
您的代码看起来不错。只需尝试将 REST URL 粘贴到您的浏览器上。由于它是一个 GET 请求,如果有任何东西从服务器返回,它会在浏览器窗口上打印出来。
-
@Gaara,我尝试在浏览器上粘贴 url 并正确打印响应..
标签: java javascript jquery html