简体   繁体   中英

How to format returned json response from servlet using jquery ajax

I am trying to present the list of users returned from servlet called using jquery ajax. The first script block works perfectly well but could not pass the form parameters like text and dropdown list value but presents the list of users returned from server in well formatted list.

The script that formats the response but cannot pass the form parameters to servlet .

$(document).ready(function() {
    $("form").submit(function(){
        alert("form submitted");
        $.get('SearchUserServlet', function(responseJson) {
            alert(responseJson);
            alert("inside the servlet");
            var $ul = $('<ul class="list-group">').appendTo($('.well'));
            $.each(responseJson, function(index, item) {
                $('<li class="list-group-item"><strong>').text(item).appendTo($ul);
            });
        });
    });
});

The second script i tried passes the form parameters properly to the servlet but the response returned from the servlet does not get formatted like the first script does. Below is the second script

var form = $('#SearchForm');

form.submit(function(){
    type: form.attr('method'),url: form.attr('action'),data: form.serialize(),
    success: function(responseJson) {
        alert(responseJson);
        alert("inside the servlet");
        var $ul = $('<ul class="list-group">').appendTo($('.well'));
        $.each(responseJson, function(index, item) {
            $('<li class="list-group-item"><strong>').text(item).appendTo($ul);
        });
    });
});

please help me find the problem in the two scripts so that i can pass the form parameters as well get the response formatted in proper list. Please review and advice.

Try this assuming your json strin is jsonString={...,..,..};

for(i=0; i<data.jsonString.length; i++) {
    //do your work here with which you are doing inside $.each  
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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