How can I return an array / json object containing json objects via an ajax php call?

Basically what I'm trying to do is return the results of a mysql query. I know how to put each row of query results in my own JSON object, now I just struggle to get multiple rows of results to return it to my jquery. In my jquery, I call the $ .ajax () function, and I have no problem with that. My problem is in the success part, where I want to be able to do something like the following:

$.ajax ({
        type: "POST",
        url:"select.php",
        data: {columns : "*",
               table : "tbUsers",
               conditions : "" },
        success: function(results) {
            foreach (results as obj)
            {
                JSON.parse(obj);
                $("#page").html(obj.id + " " + obj.name);
            }
        }
    });

, , JSON. - , php. , , ?

php - :

[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]
+4
5

php

echo json_encode($result); // result may contain multiple rows

success

success: function(results) {
    var htmlStr = '';
    $.each(results, function(k, v){
        htmlStr += v.id + ' ' + v.name + '<br />';
   });
   $("#page").html(htmlStr);
}

, .

+10

- :

$.ajax ({
    type: "POST",
    url:"select.php",
    data: {columns : "*",
        table : "tbUsers",
        conditions : "" },
    dataType: "json",
    success: function(results) {
        for( var i in results) {
            $("#page").html(results[i].id + " " + results[i].name);
        }

    }
});

dataType: "json" - JSON .

+3

, JSON

json . , json ( json).

ajax, jquery .

$.ajax({
    url: ' your/url ',
    type: 'POST',
    dataType: 'json',
    data: {param1: 'value1'},
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

http://api.jquery.com/jQuery.ajax/

: jqXHR.success(), jqXHR.error() jqXHR.complete() jQuery 1.8. , jqXHR.done(), jqXHR.fail(), jqXHR.always().

0

JSON. JSON .

JSON ( )

{ "objects": [(first object), (second object), ... ] }

:

var obj = JSON.parse(results);
jQuery.each(objs, function(i, obj) {
  $("#page").html(obj.id + " " + obj.name);
});
0

return . . JSON. JSON . JSON ( )

-1

All Articles