如何通过$ .get传递数组?

时间:2012-03-15 00:49:47

标签: javascript ajax jquery

我有以下代码:

var social_buttons_array = [];
social_buttons_array["google"] = $("input[name='social_popup_google']").is(":checked") ? 1 : 0;
social_buttons_array["twitter"] = $("input[name='social_popup_twitter']").is(":checked") ? 1 : 0;
social_buttons_array["twitter_follow"] = $("input[name='social_popup_twitter_follow']").is(":checked") ? 1 : 0;
social_buttons_array["facebook"] = $("input[name='social_popup_facebook']").is(":checked") ? 1 : 0;

我试图像这样传递数组:

$.get(
    ajaxurl,
    {
        action: 'process_data',
        get: 'social_popup',
        social_buttons_array : social_buttons_array // not works
    },
    function(response) {
    },
    'json'
    );

这不起作用。有没有想过传递数组?


EDIT&&溶液

我编辑此问题以将associative array替换为将充当数组的对象。

var social_buttons_array = new Object();
social_buttons_array.google = $("input[name='social_popup_google']").is(":checked") ? 1 : 0;
social_buttons_array.twitter = $("input[name='social_popup_twitter']").is(":checked") ? 1 : 0;
social_buttons_array.twitter_follow = $("input[name='social_popup_twitter_follow']").is(":checked") ? 1 : 0;
social_buttons_array.facebook = $("input[name='social_popup_facebook']").is(":checked") ? 1 : 0;

$.get(
    ajaxurl,
    {
        action: 'process_data',
        get: 'social_popup',
        social_buttons_array : JSON.stringify(social_buttons_array) // it works great over an object
    },
    function(response) {
    },
    'json'
    );

要在php中管理这个数组/对象,我们需要:

$social_buttons_array = json_decode(stripslashes($_GET['social_buttons_array']));

然后我们必须将此var作为对象进行管理:

echo $social_buttons_array->google
// results in 1 or 0

2 个答案:

答案 0 :(得分:3)

使用JSON.stringify()序列化?

social_buttons_array : JSON.stringify(social_buttons_array)

答案 1 :(得分:1)

GET请求将您的值放在以下格式的URL中:

page.php?arg1=value&arg2=value2

所以你不能只传递一个关联数组,除非你以某种方式将它转换为字符串值(可能是Json格式,如建议的反义词)。

另一个选项可能是将字典的每个键作为URL参数传递。

var urlParams  = {
    action: 'process_data',
    get: 'social_popup',
};

for (key in social_buttons_array) {
    urlParams[key] = social_buttons_array[key];
}

$.get(ajaxurl, urlParams, function(data) {
  $('.result').html(data);
});

会发送这样的内容:

page.php?action=process_data&get=social_popup&google=0&twitter=0&twitter_follow=0&facebook=0

这实际上取决于您将如何在服务器端处理该数据。