我有一个JSON
编码数组,我将其返回到AJAX
请求。
我需要将JSON
数组放入JS数组中,这样我就可以遍历每个数据数组来执行操作。
问。如何有效地将JSON
数组内容放入JS
数组?
PHP / JSON返回AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
答案 0 :(得分:1)
您可以使用JSON.parse
功能执行此操作:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
如果您使用的是jQuery,也可以使用jQuery.parseJSON()
,但如果可用的话,jQuery也会使用相同的函数under the hood。
答案 1 :(得分:1)
添加到Safraz答案:
如果你正在使用jQuery
,还有另一种方法可以做到这一点。只需将json
作为最后一个参数添加到ajax
来电。它告诉jQuery
将返回一些json
内容,因此success
函数已经被解析json
。
下面的示例显示了实现此目的的简单方法。有一个简单的json
属性访问(result.message
),以及遍历整个数组/对象的each
循环。如果您将返回包含对象列表的更多结构化json,则可以在each
循环调用value.objectfield
内访问它。
示例:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)