Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

jquery - How can I return an array/json object containing json objects through an ajax php call?

Basically what I'm trying to do is returning the results of a mysql query. I know how to put each row of the query results into its own JSON object, now I'm just struggling with a way so that if there's multiple lines of results to return it to my jquery. In my jquery I call the $.ajax() function and I don't have any issues with that. My problem lies within 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);
            }
        }
    });

I want to be able to iterate through the result variable like an array of JSON objects. The results variable is a string that consists of All the output of the php file. So let my question rather then be, how can I change it so that the function gets an array or how do I change it into one?

My php file currently returns something like this:

[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the php you can use

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

In your success callback you can use

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

A Demo to help you understand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...