简体   繁体   English

jQuery:在.serializeArray()中推送值;

[英]jQuery: pushing values in .serializeArray();

I'm working on an AJAX form submition in jQuery. 我正在jQuery中进行AJAX表单提交。

I used the .serializeArray() function for serializing the form, but I need to add an element to the obtained object, so I used the push() function. 我使用.serializeArray()函数对表格进行序列化,但是我需要在获取的对象中添加一个元素,因此我使用了push()函数。

So it may look like that: 因此可能看起来像这样:

{
    name: "Test",
    surname: "Test",
    action: "register"
}

When I serialize the form, the name and surname field will be sent, but the action field will not. 当我序列化表格时,将发送名称和姓氏字段,但不会发送操作字段。 I send the informations to a PHP echo function but, like the console.log() result, it will show the name and the surname, but not the action. 我将信息发送到PHP echo函数,但与console.log()结果一样,它将显示名称和姓氏,但不显示操作。

I tried the .serialize() function to, but I'll still not obtain what needed. 我尝试使用.serialize()函数,但仍无法获得所需的内容。

Here is a fiddle . 这是一个小提琴

$(document).ready(function () {
    $("#register").on("submit", function (e) {
        e.preventDefault();

        var data = $("#register").serializeArray();
        data.push({name: "action", value: "register"});

        console.log(data);

        jQuery.post("/echo/json/", data,
            function () {
                alert("Success");
            },
        "json");
    });
});

The issue is that you are binding an event handler, but you are not preventing the form from submitting like the default behavior. 问题在于您要绑定事件处理程序,但并不能像默认行为一样阻止表单提交。 You can fix this by adding return false; 您可以通过添加return false;来解决此问题return false; at the end of the event handler, but there are better ways (search google for jQuery prevent form submit). 在事件处理程序的末尾,但是有更好的方法(在Google上搜索jQuery阻止表单提交)。 You also need to bind $('#register').submit instead of $("#registerSubmit").click (this makes the enter button work as well) 您还需要绑定$('#register').submit而不是$("#registerSubmit").click (这使Enter按钮也可以工作)

The problem is that you are sending two requests, so disable form submit: 问题是您要发送两个请求,因此请禁用表单提交:

$( '#register' ).on( 'submit', function() {
    return false;
});

Or you can just place the submit button outside the form. 或者,您可以将“提交”按钮放在表单外部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM