0
var dataArray = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

$.ajax({
    type: 'POST',
    url: 'showdata.php',
    data: {data : dataArray},
    success: function(data) {
        //only the value of last selected checkbox value is returned ,
// but when I alert the dataArray then it shows all values separated with commas.
            alert('response data = ' + data);
        }
    });

showdata.php

$data = ''; 

if (isset($_POST['data']))
{
    $data = $_POST['data'];
}



echo $data;
4

2 に答える 2

1

$("input:checked")ではなく、を使用する必要があります$('input:checkbox:checked')

Javascript:

var dataArray = {'data': $("input:checked").map(function() {
    return this.value;
}).get()};

$.ajax({
    type: 'POST',
    url: 'showdata.php',
    data: dataArray,
    success: function(data) {
        alert('response data = ' + data);
    });

PHP:

$data = ''; 

if (isset($_POST['data']))
{
    $data = implode(', ', $_POST['data']);
}



echo $data;
于 2012-10-28T12:31:16.843 に答える
0

$_POSTasキーではdataなく、コントロール名(シリアル化)または指定した明示的なキー名(明示的な例)として入ってきます。

成功のコールバックは、PHP ファイルによって出力されたデータの結果を取得します。

$.ajax({
    type: 'POST',
    url: 'showdata.php',
    data: $("myformid_in_html").serialize(),
    success: function(data) {
        //only the value of last selected checkbox value is returned ,
        // but when I alert the dataArray then it shows all values separated with commas.
        alert('response data = ' + data);
    }
});

上記の例では、すべてのチェックボックスを 1 つのフォームに配置すると、すべてを一度に取得できます。

または明示的に:

$.ajax({
    type: 'POST',
    url: 'showdata.php',
    data: {
        mypostvar: "testing_service",
        myotherpostvar: 1
    },
    success: function(data) {
        //only the value of last selected checkbox value is returned ,
        // but when I alert the dataArray then it shows all values separated with commas.
        alert('response data = ' + data);
    }
});

次に、内部に名前があります。

$data = ''; 

if (isset($_POST))
{
    $data = $_POST['myformfield_html_name'];
    // or
    $mypostvar = $_POST['mypostvar'];
    $myotherpostvar = $_POST['myotherpostvar'];
}

これが主な問題です。POST データを正しく処理していません。チェックボックスは、チェックされている場合にのみ POST vars に存在します。チェックされていない場合は、中にありません。

于 2012-10-28T12:31:18.537 に答える