简体   繁体   中英

Parsing a JSON object (list of object) through Javascript and loop in it?

Ok, I know there's something wrong but I can't understand what.

I read an ArrayList of Service (in JSON mediatype) from a web service that I wrote. Going to that address returns me the json string.

Now I'm trying to make a web page for showing that values and seeing the changes making to the page a request every 3 secs.

How can I parse it, or use it? Read lot and more and I'm still to the start..

[Is not possible to pass this object to the JSP and parse, loop and everything with JSTL? That would be awesome!]

Here the js code:

 <script type="text/javascript">
setInterval(function(){
    $.ajax({ url: "/MyApp/rest/display", success: function(data){
        var objs = $.parseJSON(data);
        $.each(objs, function(i,service) {
            $("#service").append('<p>'+service+'</p>');
        });
    }, dataType: "json"});
}, 3000);
</script>

I've a <div id="service">

EDIT: Almost there!

Now I've this:

<script type="text/javascript">
setInterval(function(){
    $.ajax({ url: "/myApp/rest/display", success: function(data){
        $.each(data, function(i,service) {
            var cont = 1;
            var newdiv = document.createElement('div');
            newdiv.setAttribute('id', "service"+i);
            $("#service"+i).html('<p>'+service.serviceId+" "+service.queue.lastNumber+'</p>');
            document.getElementById("services").appendChild(newdiv);
            cont++;
        });
    }, dataType: "json"});
}, 5000);
</script>

It gets the updates and all (nice!) but I've one problem: it keeps creating new divs inside the bigger one (empty divs). How can I avoid this?

EDIT2:

Nevermind, I've done! Just add this line before the appendChild:

if(!$("#service"+i).length)

Works like a charm. Thanks!

With JQuery you do not need to parse the data since it is already parsed as JSON when you set the dataType: "json" .

$.ajax({ 
    url: "/MyApp/rest/display", 
    success: function(data) {
        $.each(data, function(i,service) {
            $("#service").append('<p>'+service+'</p>');
        });}, 
    dataType: "json" });

PS. If that doesn't work, please post the JSON that is being returned by your AJAX call.

EDIT: Here is the JSTL way of doing things: Create a JSF or JSP that does NOT return a full HTML page but just what you want inside the #service div. Lets call the page doit.jsp . Now we can just use ajax to put that in the #service div.

$.ajax({
    url: "doit.jsp",
    success: function(data) { $("#service").html(data); });

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