如何使用$ .ajax发送数组 - dataType:json?

时间:2013-09-30 19:31:00

标签: javascript jquery ajax arrays json

我目前正在尝试将javascript数组发送到我的.php文件处理程序并将其保存到我的数据库中。

请求成功但是我的数组似乎没有正确发布/保存。 在我的POST请求源中,它只显示为:round_items%5B%5D=1

我错过了什么?

id = 5;
var roundChallenges = new Array("item1", "item2", "etc");

//Save the data
var url = path.php;

var request = $.ajax({
    type: "POST",
    url: url,
    dataType: 'json',
    data: { uid: id, round_items: roundChallenges },

    success: function(data)
    {....

1 个答案:

答案 0 :(得分:1)

round_items%5B%5D=1是正确的。这就是应该发送的内容。这解码为round_items[]=1,这就是你在查询字符串中创建数组的方法。

将对象传递给$.ajax时,jQuery会将其转换为查询字符串,即标准传输格式。

在PHP中,您不需要json_decode或任何其他内容。它会将它解析为$_POST$_POST['round_items']将是一个数组,$_POST['uid']将是您的id