gpt4 book ai didi

java - 从servlet获取json响应并显示在jsp表中?

转载 作者:行者123 更新时间:2023-11-28 08:58:25 24 4
gpt4 key购买 nike

我正在调用 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 中,它有从数据库返回的数据并使用调试进行验证。我在这里遗漏了什么吗?

谢谢!

最佳答案

我在您的 Ajax 请求中看不到“dataType”,例如:

数据类型:'json'

尝试添加它。

所以,它将变成:

$.ajax({
type: "GET",
url: "./dataFetchController",
success: function(responseJson) {
//alert and success handler
},
dataType: 'json',
error : function(){
// error handler
});

dataType 是您期望从服务器返回的数据类型

关于java - 从servlet获取json响应并显示在jsp表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18120751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com