简体   繁体   English

如何提交动态生成的表单到AJAX?

[英]How to submit a dynamically generated form to AJAX?

I have an AJAX call which dynamically generates a HTML form. 我有一个AJAX调用,可以动态生成HTML表单。 This form contains a number of elements including inputs, selects, textareas, checkboxes as well as etc. 该表单包含许多元素,包括输入,选择,文本区域,复选框等。

I need to write some javascript (jquery available) to get all the fields in this form and submit them to an AJAX script. 我需要编写一些javascript(可用的jquery)以获取此表单中的所有字段并将其提交给AJAX脚本。 I won't know how many or what fields are there (only a basic idea) as it all depends on what the user does. 我不知道有多少个字段或什么字段(仅是一个基本概念),因为这完全取决于用户的操作。

Any ideas how to do this? 任何想法如何做到这一点? Lets say my form name is 'ajaxform' 可以说我的表单名称是“ ajaxform”

As everyone said, use jQuery serialize . 众所周知,使用jQuery serialize One other note is to override your form submit (if needed) via jQuery live method: 另一个注意事项是通过jQuery live方法重写表单提交(如果需要):


    //Override form submit
    $("form").live("submit", function (event) {
        event.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr('action'), // Get the action URL to send AJAX to
            type: "POST",
            data: form.serialize(), // get all form variables
            success: function(result){
                // ... do your AJAX post result
            }
        });
    });

var string_ready_to_be_posted = $("#formId").serialize();

http://api.jquery.com/serialize/

You can use jQuery's .serialize() : 您可以使用jQuery的.serialize()

var data = $('#ajaxform').serialize();
var action = $('#ajaxform').attr('action');
$.post(action, data, function(data) {
 ...
});

var string_ready_to_be_posted = $('form[name="ajaxform"]').serialize(); As addon for using NAME-selector instead of ID 作为使用NAME选择器而非ID的插件

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

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