我使用$.getJSON()
传递一些数据到服务器端(PHP, Codeigniter),并使用返回数据做一些工作。我发送给服务器的数据是以数组的形式。
问题:向服务器发送关联数组时,服务器端没有收到结果。但是,如果发送带有数字索引的普通数组,则在服务器端接收数据。如何将数据数组发送到服务器?
JS Code (Not Working)
boundary_encoded[0]['testA'] = 'test';
boundary_encoded[0]['testB'] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
JS代码
boundary_encoded[0][0] = 'test0';
boundary_encoded[0][1] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
PHP代码$boundary_encoded = $_GET['boundary_encoded'];
print_r($_GET);
错误味精
<b>Notice</b>: Undefined index: boundary_encoded in <b>C:'xampp'htdocs'test'boundary'boundary_encoded_insert_into_db_ajax.php</b> on line <b>11</b><br />
Array
(
)
工作结果Array
(
[boundary_encoded] => Array
(
[0] => Array
(
[0] => test
[1] => test1
)
)
)
这不起作用的原因是JavaScript不支持关联数组。这个任务:
boundary_encoded[0]['testA'] = 'test';
看起来在JS中起作用,因为你可以给任何对象分配一个新的属性,包括数组。但是,它们不会在for
循环中枚举。
而必须使用对象字面值:
boundary_encoded[0] = {'testA':'test'};
您可以使用JSON.stringify
将boundary_encoded
转换为JSON字符串,将其发送到服务器,并使用PHP的json_decode()
函数将字符串转换回对象数组。
我建议将数组转换为JSON。如果你不能在PHP中这样做(使用json_encode函数),这里有几个JS等效的:
- http://phpjs.org/functions/json_encode: 457
- http://www.openjs.com/scripts/data/json_encode.php
在getJSON调用中,使用
{boundary_encoded: JSON.stringify(boundary_encoded)},
代替
{boundary_encoded: boundary_encoded},