Kan*_*iya 3 javascript php arrays ajax jquery
我使用JSON.stringify方法将数组传递给服务器.
我有一个有4个元素的数组:
arr[10] = 1;
arr[20] = 1;
arr[30] = 1;
arr[40] = 1;
Run Code Online (Sandbox Code Playgroud)
然后我这样做:
arr = JSON.stringify(arr);
Run Code Online (Sandbox Code Playgroud)
然后将其发送到服务器:
jQuery.ajax({
type: "post",
url: baseurl+"profile/mprofile/action/ratings/add_ratings",
data:{"checkbox":checkbox,"review":review,"speciality":speciality,"arr":arr},
success: function(data, status) {
jQuery('#header-error').html(data);
}
});
Run Code Online (Sandbox Code Playgroud)
我在PHP中获取数组:
$arr = $this->ci->input->post('arr');
$arr = json_decode($arr);
print_r($arr) ; die ;
Run Code Online (Sandbox Code Playgroud)
结果是
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] => 1
[11] =>
[12] =>
[13] =>
[14] =>
[15] =>
[16] =>
[17] =>
[18] =>
[19] =>
[20] => 1
[21] =>
[22] =>
[23] =>
[24] =>
[25] =>
[26] =>
[27] =>
[28] =>
[29] =>
[30] => 1
[31] =>
[32] =>
[33] =>
[34] =>
[35] =>
[36] =>
[37] =>
[38] =>
[39] =>
[40] => 1
)
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
这就是javascript数组的工作方式.将值设置为超出范围的索引时,将展开数组,成功设置值并将所有"缺失"值设置为undefined.
您被PHP行为所破坏,这种行为混合了数组和字典(或"关联数组",PHP谈话)之间的差异.
要避免此行为,只需在javascript而不是数组中创建字典.
var arr = {};
arr[10] = 1;
arr[20] = 2;
Run Code Online (Sandbox Code Playgroud)
此外,在PHP端,您应该true作为第二个参数传递给json_decode.
json_decode($arr, true)
Run Code Online (Sandbox Code Playgroud)
这将使它返回数组而不是stdclass.
| 归档时间: |
|
| 查看次数: |
822 次 |
| 最近记录: |