繁体   English   中英

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

[英]Getting json response from servlet and display in jsp table?

我正在调用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”,例如:

dataType:'json'

尝试添加它。

因此,它将变为:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM