发送具有选中的Checkbox值的数组,并在php中作为字符串检索

时间:2018-07-05 11:17:41

标签: php ajax

我正在将选中的复选框值发送到数组中的php。

// tag =['Apple','Mango','Tomato']
var tag =  $(this).children().siblings().children().children('input[name="cb"]:checked');
        var tagData = [];
        $.each(tag, function() {
            tagData.push($(this).val());
        });

        console.log(tagData);
$.ajax({
    type: "POST",
    url: "script.php",
    data: {tag: tagData }, 
    cache: false,

    success: function(){
        alert("OK");
    }
});

Console.log数据

(2) ["Apple", "Apple"]
0: "Apple"
1: "Apple"
length: 2__proto__: Array(0)

我在php中得到这样的数组。

 $list = $_POST['tag'];
 $imgTag = implode( ", ",$list);
 // i want like this - $imgTag = "Apple,Mango,Tomato".

但是我在php中出现空行。

1 个答案:

答案 0 :(得分:1)

在发送ajax请求时,使用JSON.stringify序列化您的tagData。像这样

$.ajax({
    type: "POST",
    url: "script.php",
    data: {tag: JSON.stringify(tagData) }, 
    cache: false,

    success: function(){
        alert("OK");
    }
});