问题描述
基本上我试图做的是返回一个MySQL查询的结果。我知道如何把查询结果的每一行到它自己的JSON对象,现在我只是一个办法挣扎,这样,如果有多个行的结果将其返回到我的jQuery。在我的jQuery我所说的$。阿贾克斯()函数,我没有与任何问题。我的问题就在于成功的一部分,在这里我希望能够像做以下范围内:
$。阿贾克斯({
键入:POST,
网址:select.php
数据:{列:*,
表:tbUsers
条件:},
成功:函数(结果){
的foreach(结果OBJ)
{
JSON.parse(OBJ);
$(#页)HTML(obj.id ++ obj.name)。
}
}
});
我希望能够遍历像JSON对象的数组结果变量。结果变量是一个字符串,它由php文件的所有输出。因此,让我的问题而不是是,我如何改变它,这样的功能得到一个数组或我怎么改变成一个?
我的PHP文件,目前正在返回是这样的:
[{0:1,1:名1,ID:1,名:名1},{0:2, 1:名2,ID:2,名:名2}]
在 PHP
您可以使用
回声json_en code($结果); //结果可能包含多行
在你的成功
回调可以使用
成功:函数(结果){
VAR htmlStr ='';
$每个(结果,函数(K,V){
htmlStr + = v.id +''+ v.name +'< BR />';
});
$(#页)HTML(htmlStr)。
}
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"}]
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.
这篇关于我怎样才能返回通过AJAX调用PHP包含JSON对象的数组/ JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!