在 Jquery 中,我创建两个数组,一个嵌入另一个数组,就像这样......
arrayOne = [{name:'a',value:1}, {name:'b',value:2}]
var arrayTwo = [{name:'foo',value:'blah'},{name:'arrayOne',value:arrayOne}];
然后我将其通过 Ajax 放入,并通过另一端的 PHP 提取变量。 print_r($arrayTwo) 的结果如下...
Array([foo] => blah [arrayOne] => [object Object],[object Object])
我看不到如何提取 arrayOne 的内容,这很遗憾,因为我真的需要它们!谁能告诉我我在 Jquery 中做错了什么,或者我需要在 PHP 中做什么才能使嵌入式数组可访问。
一如既往地非常感谢
编辑以添加我的 Ajax 代码...
$.ajax({
type: "POST",
url:'actions.php',
data:arrayTwo,
datatype:'json',
cache: false,
success: function(data){
}
})
问题是 jQuery 的 $.ajax
(或者更确切地说 $.param
)方法以特殊方式处理对象数组。 jQuery 将使用 tên
作为参数名称,并使用 giá trị
của字符串表示形式作为值:
> $.param([{name: 'foo', value: 42}, {name: 'bar', value: 21}])
"foo=42&bar=21"
Nhưng arrayOne
的字符串表示是您在服务器上看到的无用的东西:
> [{name:'a',value:1}, {name:'b',value:2}].toString()
"[object Object],[object Object]"
tài liệu实际上指出了传递数组/对象时的注意事项:
If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()
[
{ name: "first", value: "Rick" },
{ name: "last", value: "Astley" },
{ name: "job", value: "Rock Star" }
]
Note: Because some frameworks have limited ability to parse serialized arrays, developers should exercise caution when passing an obj
argument that contains objects or arrays nested within another array.
Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.
由于您有复杂的数据结构,您可能应该使用 JSON 来编码您的数据:
data: {data: JSON.stringify(arrayTwo)},
在服务器上您只需使用它进行解码
$data = json_decode($_POST['data'], true);
$data
sẽ có điều tương tự arrayTwo
完全相同的结构。
但是如果您实际上想要具有名称为 foo
Và arrayOne
的参数,那么您只需序列化 arrayOne
的值即可:
data: [
{name:'foo',value:'blah'},
{name:'arrayOne',value: JSON.stringify(arrayOne)}
],
在 PHP 中:
$arrayOne = json_decode($_POST['arrayOne'], true);
Tôi là một lập trình viên xuất sắc, rất giỏi!