小编典典

通过jQuery ajax()将多个复选框数据发送到PHP

php

我想通过jQuery的.ajax()在我的网站上提交一个POST表单,该表单包含一个textarea字段和一个输入字段(类型为“
checkbox”,其中复选框的数量为任意/可变)。PHP接收到textarea数据,并且ajax响应已正确显示给用户。但是,PHP似乎没有收到复选框数据(是否选中了复选框)。我该如何工作?这是我的代码:

HTML:

<form method="post" action="myurl.php" id=myForm>
    <textarea id="myField" type="text" name="myField"></textarea>
    <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
    <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
    ...(maybe some more checkboxes - dynamically generated as necessary)
    <input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>

jQuery:

function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {

        var myCheckboxes = new Array();
        $("input:checked").each(function() {
           myCheckboxes.push($(this).val());
        });

        $.ajax({
            type: "POST",
            url: "myurl.php",
            dataType: 'html',
            data: { myField:$("textarea[name=myField]").val(),
                    myCheckboxes:myCheckboxes },
            success: function(data){
                $('#myResponse').html(data)
            }
        });
        return false;
});
});

现在,PHP

$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
    for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
    {
        // do some stuff, save to database, etc.
    }
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);

一切正常:提交表单时,新记录存储在我的数据库中,响应返回到网页,但复选框数据未发送。我想知道已选中哪个复选框(如果有)。我已经读过有关.serialize(),JSON等的信息,但是这些都没有用。我必须在jQuery和PHP中进行序列化/
JSON吗?怎么样?使用复选框发送表单数据时,一种方法比另一种方法好吗?我已经坚持了两天。任何帮助将不胜感激。提前谢谢!


阅读 660

收藏
2020-05-29

共1个答案

小编典典

var myCheckboxes = new Array();
$("input:checked").each(function() {
   data['myCheckboxes[]'].push($(this).val());
});

您将复选框推到错误的数组data['myCheckboxes[]']而不是myCheckboxes.push

2020-05-29