我有一个名为orderproductForm的表单和未定义数量的输入。

我想用jQuery。get或ajax或类似的东西会通过ajax调用一个页面,并发送orderproductForm表单的所有输入。

我想有一种方法是

jQuery.get("myurl",
          {action : document.orderproductForm.action.value,
           cartproductid : document.orderproductForm.cartproductid.value,
           productid : document.orderproductForm.productid.value,
           ...

然而,我不知道确切地所有表单输入。是否有一个特性,功能或一些东西,只是发送所有的表单输入?


当前回答

这不是OP问题的答案, 但如果你不能使用静态形式的DOM,你也可以这样尝试。

var $form = $('<form/>').append(
    $('<input/>', {name: 'username'}).val('John Doe'),
    $('<input/>', {name: 'user_id'}).val('john.1234')
);

$.ajax({
    url: 'api/user/search',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    data: $form.serialize(),
    success: function(data, textStatus, jqXHR) {
        console.info(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        var errorMessage = jqXHR.responseText;
        if (errorMessage.length > 0) {
            alert(errorMessage);
        }
    }
});

其他回答

你可以使用Ajax Form Plugin或jQuery serialize函数中的ajaxForm/ajaxSubmit函数。

AjaxForm:

$("#theForm").ajaxForm({url: 'server.php', type: 'post'})

or

$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})

当按下提交按钮时,ajaxForm将发送。ajaxSubmit立即发送。

序列化:

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theForm').serialize())

AJAX序列化文档在这里。

我真的很喜欢superluminary的这个答案,尤其是他在jQuery插件中包装解决方案的方式。所以感谢superluminary提供了一个非常有用的答案。在我的例子中,我想要一个插件,它允许我在插件初始化时通过选项来定义成功和错误事件处理程序。

这就是我想到的:

;(function(defaults, $, undefined) {
    var getSubmitHandler = function(onsubmit, success, error) {
        return function(event) {
            if (typeof onsubmit === 'function') {
                onsubmit.call(this, event);
            }
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize()
            }).done(function() {
                if (typeof success === 'function') {
                    success.apply(this, arguments);
                }
            }).fail(function() {
                if (typeof error === 'function') {
                    error.apply(this, arguments);
                }
            });
            event.preventDefault();
        };
    };
    $.fn.extend({
        // Usage:
        // jQuery(selector).ajaxForm({ 
        //                              onsubmit:function() {},
        //                              success:function() {}, 
        //                              error: function() {} 
        //                           });
        ajaxForm : function(options) {
            options = $.extend({}, defaults, options);
            return $(this).each(function() {
                $(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
            });
        }
    });
})({}, jQuery);

这个插件允许我很容易地在页面上“ajaxify”html表单,并提供onsubmit,成功和错误事件处理程序,用于实现表单提交状态的用户反馈。这使得插件可以这样使用:

 $('form').ajaxForm({
      onsubmit: function(event) {
          // User submitted the form
      },
      success: function(data, textStatus, jqXHR) {
          // The form was successfully submitted
      },
      error: function(jqXHR, textStatus, errorThrown) {
          // The submit action failed
      }
 });

请注意,成功和错误事件处理程序接收到的参数与从jQuery ajax方法的相应事件接收到的参数相同。

我觉得很奇怪,没有人提到数据是一个对象。对我来说,这是传递数据最干净、最简单的方式:

$('form#foo').submit(function () {
    $.ajax({
        url: 'http://foo.bar/some-ajax-script',
        type: 'POST',
        dataType: 'json',
        data: {
            'foo': 'some-foo-value',
            'bar': $('#bar').val()
        }
    }).always(function (response) {
        console.log(response);
    });

    return false;
});

然后,在后端:

// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar

还有一个提交事件,可以像这样触发$("#form_id").submit()。如果表单已经很好地用HTML表示,则可以使用此方法。您只需读入页面,用东西填充表单输入,然后调用.submit()。它将使用表单声明中定义的方法和动作,因此不需要将其复制到javascript中。

例子

这是一个简单的参考:

// this is the id of the form
$("#idForm").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var actionUrl = form.attr('action');
    
    $.ajax({
        type: "POST",
        url: actionUrl,
        data: form.serialize(), // serializes the form's elements.
        success: function(data)
        {
          alert(data); // show response from the php script.
        }
    });
    
});