javascript - 在jquery php ajax中循环遍历js数组
问题描述
我正在尝试使用 ajax 循环一个 js 对象。我正在查看 json_decode 但它不起作用,因为这是一个数组而不是一个对象。
var array = [{type: 'a', value: 1}, {type: 'b', value: 1}]
$.ajax{
url: "php.php",
data: {array: array}
}
我的 php 代码将用于在数据库中为数组中的每个项目创建一个新行。我怎样才能做到这一点?
解决方案
如果你不想将它作为json 字符串发送,你应该对你的数组进行字符串化:
var array = [{type: 'a', value: 1}, {type: 'b', value: 1}]
$.ajax({
url: "php.php",
data: {array: JSON.stringify( array )}
});
在你可以用它解码之后
$arr=json_decode($_REQUEST['array'], true);
forach($arr as $row)
{
//do here whatever you want with your data:
// $row["type"]
// $row["value"]
}
但没有必要以 json 格式发送数据。如果您将其作为数组发送,则可以直接将其用作数组(不带 json_decode):
var array = [{type: 'a', value: 1}, {type: 'b', value: 1}]
$.ajax({
url: "php.php",
data: {array: array }
});
在你可以迭代它之后
forach($_REQUEST['array'] as $row)
{
//do here whatever you want with your data:
// $row["type"]
// $row["value"]
}