jQuery serializeArray 失败

jQuery serializeArray fails

考虑以下几点:

PHP:

<form id="f-submit" method="post" action="">

    <button class="btn-submit" name="update" type="submit">APPROUVE</button>

</form>

jQuery:

$("button.btn-submit").click(function(event) {
    event.preventDefault();

    var formData = $("#f-submit").serializeArray();
    formData.push({actiontype: "delete"});

    $.ajax({
        type: "POST",
        url: "includes/submit_comment.php",
        data: formData
    }).done(function(data) {

        alert(data);

    }).fail(function(data) {

        alert('Ajax failed.');

    });
});

submit_comment.php:

if (isset($_POST['actiontype'])) {

    echo 'found';

} else {

    echo 'not found';

}

出于某种原因,我总是得到 'not found'。

但是,当我发送数据时没有序列化,就像这样,

var formData = ({actiontype: "delete"});

有效!!!

所以问题肯定出在serializeArray()上,但到底是什么呢?我要为这个疯狂了...

serializeArray()生成一个由名称和值组成的对象。 您是否尝试调试 var formData = $("#f-submit").serializeArray();?在您的情况下,它应该不会产生 names/values 对,因为:

Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Data from file select elements is not serialized. jQuery doc

因此您必须添加与提交输入不同的输入。让我们检查一下这个智能解决方案:jQuery serializeArray doesn't include the submit button that was clicked

试试这个语法:

formData.push({name: 'actiontype', value: delete});