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;
答案 0 :(得分: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;
答案 1 :(得分:0)
它不会以$_POST
作为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);
}
});
使用上面的示例,如果您将所有复选框放在一个表单中,则可以一次性全部使用它们。
或明确地说:
$.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变量中,否则您将无法在其中找到它。