简体   繁体   中英

parse through Json list and append

I have been trying to basically create a div for each row of the json list returned via ajax which would append to the main div #chatcontents. However, i am facing problems with the correct syntax. I think the error is how my json is being returned.

This is the function which does the ajax call in the index.php

function returnValue()
{
 $.ajax({
            async: true,
            type: "GET",
            url: "thread.php",
            data: {lastposted : dateposted},

            success: function (json) {
                if(json)
                {
                for (var i = 0, len = json.length; i < len; ++i) {
                var results = json[i];
                var newDiv = $("<div>" + results.1 + results.2  "</div>");
                }

                   $('#chatContents').append(newDiv);             
                }
            }  
        });
}

thread.php returns a Json result like this..

[{"0":"something","1":"41234","2":"test"},
{"0":"somethingmore","1":"2131","2":"test2"}]

The codes i have seen online seem to return the key but mine are in numberics (0,1,2). I think its coz of the way i have the returned the array. It is a 2d array which was converted to JSON. I am not sure if this is causing the problem as to how i loop through the array in the first page. Any help would be appreciated.

For a clearer pic: thread.php has this code:

<META HTTP-EQUIV="Refresh" CONTENT="3">
<?php
$latestmsgs = retrieveNewMsgs($lastpost,$currtime);
  ?>

 <?php echo json_encode($latestmsgs);?>

So basically, thread.php is refreshing every 3 seconds. Index.php makes an ajax call to this page and retrieves the latest msg in the form of json and appends.

I hope its clearer.

Your thread.php is returning an array of JSON strings...you need to loop the array and then parse each string in order to get the object.

for (var i = 0, len = json.length; i < len; ++i) {
  var results = JSON.parse(json[i]);
  var newDiv = $("<div>" + results['1'] + results['2']  "</div>");
}

I think results.1 is invalid syntax, you should use results[1] .

EDIT

  1. You have syntax errors on this line (apart from the bracket syntax instead of dots, you are missing a plus sign):

     var newDiv = $("<div>" + results.1 + results.2 "</div>"); 

    It should be

     var newDiv = $("<div>" + results[1] + results[2] + "</div>"); 
  2. Make sure your callback is getting a parsed JSON object, not a raw JSON string. Alert typeof json inside the callback, it should say "object". If it says "string", add dataType: 'json' to the options object passed to $.ajax , and/or make sure the server is setting the proper content-type for the response.

  3. Once you fix that, your code should work. See this jsfiddle .

EDIT 2

  1. The line with .append should be inside of your for loop, otherwise only the last result on the JSON will be appended to the div. See updated fiddle .

  2. You said on the comments: "I am appending to a class="container" div". But your code says you're appending to a div with ID == "chatContents". Do you have such div?

  3. When you say an alert stopped working, it means there is probably some error before the alert preventing the rest of the script to execute. Check Firebug's console for errors, and double-check all code before the alert.

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