最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to submit a dynamically generated form to AJAX? - Stack Overflow

programmeradmin0浏览0评论

I have an AJAX call which dynamically generates a HTML form. 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. 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'

I have an AJAX call which dynamically generates a HTML form. 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. 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'

Share Improve this question edited Sep 9, 2011 at 14:00 genesis 51k20 gold badges98 silver badges126 bronze badges asked Sep 9, 2011 at 13:58 DavidDavid 16.8k35 gold badges110 silver badges169 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 5

As everyone said, use jQuery serialize. One other note is to override your form submit (if needed) via jQuery live method:

    //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./serialize/

You can use jQuery's .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

发布评论

评论列表(0)

  1. 暂无评论