简体   繁体   中英

Returning [object , Object] instead of correct JSON

Here is my function

function getRecords(){            
    $.getJSON( "viewcustomers.php", function(data) {
        var items = [];
        $.each( data, function( key, val ) {
            items.push( "<td>" + val + "</td>" );
            alert(items);
         });
    });
}

The data present in viewcustomers.php is below:

[{"id":"1","name":"ali","cnic":"01","address":"nipa","email":"301","phone":"luxairy "},{"id":"2","name":"raheel","cnic":"1234567","address":"abc flat","email":"raheel@gmail.com","phone":"0342"},{"id":"5","name":"Raheel","cnic":"123-4567-45","address":"Gulshan block 13-c","email":"raheel@gmail.com","phone":"03422301775"},{"id":"4","name":"zain","cnic":"12345678","address":"f.b area","email":"zain@gmail.com","phone":"7894561"},{"id":"6","name":"Raheel","cnic":"123-4567-45","address":"Gulshan block 13-c","email":"raheel@gmail.com","phone":"03422301775"},{"id":"7","name":"Ali","cnic":"123456786","address":"nipa","email":"ali@gmail.com","phone":"1234568"},{"id":"8","name":"Waqas","cnic":"123456748","address":"F.b area","email":"waqas@gmail.com","phone":"1234568"},{"id":"9","name":"Owais","cnic":"1234567","address":"Fb area","email":"owais@gmail.com","phone":"12345678"}]

But when i am running my jquery function it is giving me [object Object] instead of the above key values.

In your case item is actually an array . And you are pushing the values inside it from the JSON. So in order to view it in a string format,

You have to use,

alert(JSON.stringify(items));

While making a deeper look at your JSON, You are traversing on each objects, So you should Stringify those object while inserting into the array like,

items.push( "<td>" + JSON.stringify(val) + "</td>" );

Because the to string implementation of object returns [object Object] , you can use the JSON.stringify() to handle this. For old browser you have to include a polyfil like json2

items.push( "<td>" + JSON.stringify(val) + "</td>" );

Demo: Fiddle - look at the browser console


Update

It should be simple if you use .map()

var items = $.map(data, function (obj) {
    return "<tr>" + $.map(obj, function (val) {
        return '<td>' + val + '</td>'
    }).join('') + "</tr>";
});
console.log(items.join(''));

Demo: Fiddle

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