简体   繁体   中英

Looping through json object returned from jquery ajax call

I have returned three values from an ajax call. Here is the content of the json object in my console log:

{"no":"img2","name":"mylogo.jpg","location":"u_images\/1\/"} 

-No is meant to refer to the thumbnail div container where i want to display a thumbnail of the image uploaded by the user

-name is obviously the name of the file

-location refers to the file path where the user has uploaded the file to, where i want to grab the file and display in the thumbnail.

-1 at the end of the location is the folder which is given the id of the user.

Here is what i've tried:

   success: function(data)
    {

       if (data != '') 
       { 
            //console.log(data);

            var data = $.parseJSON(data);

            $(data).each(function(num,name,loc) //this looks stupid i know,but it's just the last   //of the hundred things i've tried-i know the fault has to lie here in my loop syntax.

       {
            var imgsrc = loc+'name'; 
            $('#'+num+'div').html('<img src="'+imgsrc+'" width="50" height="50" />');

       });

     }
 }

So when i submit the form, i get the returned object in my console log alright, but my other code to replace the loading gif image in the thumbnail with the image of the file just uploaded does not work, and i get no errors either.

Any help or advice much appreciated.

Hi just in case anyone stumbles on gthis, i just want to close it up as i got it to work thanks to lolka_bolka's lead. All i had to do was this:

  success: function(data)
  {     
    if (data != '')
    { 
     data = $.parseJSON(data);
     $(data).each(function(idx, obj) 
         {
            console.log(obj); //Check this
            var imgsrc = obj.location + obj.name;
            $('#' + obj.no + 'div').html('<img src="' + imgsrc + '" width="50" height="50" />');
        });                 
    }
}

The each function has 2 parameters, the key and the object. Check my code.

    var data = '{"no":"img2","name":"mylogo.jpg","location":"u_images\/1\/"} ';
    data = $.parseJSON(data);
    $(data).each(function(idx, obj) {
        //console.log(obj); //Check this
        var imgsrc = obj.location + 'name';
        $('#' + idx + 'div').html('<img src="' + imgsrc + '" width="50" height="50" />');

    });

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