Javascript jQuery AJAX 提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1960240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:06:05  来源:igfitidea点击:

jQuery AJAX submit form

javascriptjqueryajaxsubmitforms

提问by Nathan H

I have a form with name orderproductFormand an undefined number of inputs.

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

I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.

我想做某种 jQuery.get 或 ajax 或类似的东西,它会通过 Ajax 调用页面,并发送表单的所有输入orderproductForm

I suppose one way would be to do something like

我想一种方法是做类似的事情

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

However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?

但是我并不完全知道所有的表单输入。是否有一个特性、功能或某些东西可以只发送所有表单输入?

采纳答案by jspcal

You can use the ajaxForm/ajaxSubmit functions from Ajax Form Pluginor the jQuery serialize function.

您可以使用Ajax 表单插件中的 ajaxForm/ajaxSubmit 函数或 jQuery 序列化函数。

AjaxForm:

Ajax 表单

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

or

或者

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

ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.

ajaxForm 将在提交按钮被按下时发送。ajaxSubmit 立即发送。

Serialize:

序列化

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

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

AJAX serialization documentation is here.

AJAX 序列化文档在这里

回答by Alfrekjv

This is a simple reference:

这是一个简单的参考:

// 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 url = form.attr('action');

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


});

I hope it helps you.

我希望它能帮助你。

回答by Davide Icardi

Another similar solution using attributes defined on the form element:

另一个使用在表单元素上定义的属性的类似解决方案:

<form id="contactForm1" action="/your_url" method="post">
    <!-- Form input fields here (do not forget your name attributes). -->
</form>

<script type="text/javascript">
    var frm = $('#contactForm1');

    frm.submit(function (e) {

        e.preventDefault();

        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    });
</script>

回答by superluminary

There are a few things you need to bear in mind.

您需要牢记一些事项。

1. There are several ways to submit a form

1. 有多种方式提交表单

  • using the submit button
  • by pressing enter
  • by triggering a submit event in JavaScript
  • possibly more depending on the device or future device.
  • 使用提交按钮
  • 按回车键
  • 通过在 JavaScript 中触发提交事件
  • 可能更多取决于设备或未来的设备。

We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.

因此,我们应该绑定到表单提交事件,而不是按钮单击事件。这将确保我们的代码现在和将来适用于所有设备和辅助技术。

2. Hijax

2. Hijax

The user may not have JavaScript enabled. A hijaxpattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.

用户可能没有启用 JavaScript。一个hijax模式好这里,我们轻轻的使用JavaScript形式的控制,但离开它submittable如果JavaScript的失败。

We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.

我们应该从表​​单中提取 URL 和方法,因此如果 HTML 发生变化,我们不需要更新 JavaScript。

3. Unobtrusive JavaScript

3. 不显眼的 JavaScript

Using event.preventDefault()instead of return falseis good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.

使用event.preventDefault()而不是return false是一种很好的做法,因为它允许事件冒泡。这允许其他脚本与事件相关联,例如可能正在监视用户交互的分析脚本。

Speed

速度

We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.

理想情况下,我们应该使用外部脚本,而不是内联插入我们的脚本。我们可以使用脚本标签在页面的头部链接到它,或者在页面底部链接到它以加快速度。脚本应该悄悄地增强用户体验,而不是妨碍。

Code

代码

Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:

假设您同意上述所有内容,并且您想捕获提交事件,并通过 AJAX(hijax 模式)处理它,您可以执行以下操作:

$(function() {
  $('form.my_form').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: form.serialize()
    }).done(function(data) {
      // Optionally alert the user of success here...
    }).fail(function(data) {
      // Optionally alert the user of an error here...
    });
  });
});

You can manually trigger a form submission whenever you like via JavaScript using something like:

您可以使用以下内容通过 JavaScript 随时手动触发表单提交:

$(function() {
  $('form.my_form').trigger('submit');
});

Edit:

编辑:

I recently had to do this and ended up writing a plugin.

我最近不得不这样做并最终编写了一个插件。

(function($) {
  $.fn.autosubmit = function() {
    this.submit(function(event) {
      event.preventDefault();
      var form = $(this);
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize()
      }).done(function(data) {
        // Optionally alert the user of success here...
      }).fail(function(data) {
        // Optionally alert the user of an error here...
      });
    });
    return this;
  }
})(jQuery)

Add a data-autosubmit attribute to your form tag and you can then do this:

将 data-autosubmit 属性添加到您的表单标签,然后您可以执行以下操作:

HTML

HTML

<form action="/blah" method="post" data-autosubmit>
  <!-- Form goes here -->
</form>

JS

JS

$(function() {
  $('form[data-autosubmit]').autosubmit();
});

回答by macio.Jun

You can also use FormData(But not available in IE):

您还可以使用FormData(但在 IE 中不可用):

var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector        
$.ajax({
    type: "POST",
    url: "yourURL",// where you wanna post
    data: formData,
    processData: false,
    contentType: false,
    error: function(jqXHR, textStatus, errorMessage) {
        console.log(errorMessage); // Optional
    },
    success: function(data) {console.log(data)} 
});

This is how you use FormData.

这就是您使用FormData 的方式

回答by Timo Huovinen

Simple version (does not send images)

简单版(不发图片)

<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
    (function($){
        $("body").on("submit", ".my-form", function(e){
            e.preventDefault();
            var form = $(e.target);
            $.post( form.attr("action"), form.serialize(), function(res){
                console.log(res);
            });
        });
    )(jQuery);
</script>

Copy and paste ajaxification of a form or all forms on a page

复制并粘贴页面上的表单或所有表单的ajaxification

It is a modified version of Alfrekjv'sanswer

这是Alfrekjv答案的修改版本

  • It will work with jQuery >= 1.3.2
  • You can run this before the document is ready
  • You can remove and re-add the form and it will still work
  • It will post to the same location as the normal form, specified in the form's "action" attribute
  • 它适用于 jQuery >= 1.3.2
  • 您可以在文档准备好之前运行它
  • 您可以删除并重新添加表单,它仍然可以工作
  • 它将发布到与正常表单相同的位置,在表单的“action”属性中指定

JavaScript

JavaScript

jQuery(document).submit(function(e){
    var form = jQuery(e.target);
    if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
        e.preventDefault();
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: form.serialize(), // serializes the form's elements.
            success: function(data) {
                console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
            }
        });
    }
});

I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.

我想编辑 Alfrekjv 的答案,但偏离太多,所以决定将此作为单独的答案发布。

Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.

不发送文件,不支持按钮,例如点击按钮(包括提交按钮)将其值作为表单数据发送,但因为这是一个ajax请求,按钮点击不会被发送。

To support buttons you can capture the actual button click instead of the submit.

为了支持按钮,您可以捕获实际的按钮点击而不是提交。

jQuery(document).click(function(e){
    var self = jQuery(e.target);
    if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
        e.preventDefault();
        var form = self.closest('form'), formdata = form.serialize();
        //add the clicked button to the form data
        if(self.attr('name')){
            formdata += (formdata!=='')? '&':'';
            formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
        }
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: formdata, 
            success: function(data) {
                console.log(data);
            }
        });
    }
});

On the server side you can detect an ajax requestwith this header that jquery sets HTTP_X_REQUESTED_WITHfor php

在服务器端,您可以使用 jquery 为 php设置的此标头检测 ajax 请求HTTP_X_REQUESTED_WITH

PHP

PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //is ajax
}

回答by Shaiful Islam

This code works even with file input

即使使用文件输入,此代码也能工作

$(document).on("submit", "form", function(event)
{
    event.preventDefault();        
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {


        }
    });        
});

回答by BruceHill

I really liked this answerby superluminaryand especially the way he wrapped is solution in a jQueryplugin. So thanks to superluminaryfor a very useful answer. In my case, though, I wanted a plugin that would allow me to define the successand errorevent handlers by means of options when the plugin is initialized.

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

So here is what I came up with:

所以这就是我想出的:

;(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);

This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, successand errorevent handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:

这个插件让我可以很容易地在页面上“ajaxify”html表单,并提供onsubmitsuccesserror事件处理程序,用于向用户反馈表单提交的状态。这允许插件如下使用:

 $('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
      }
 });

Note that the successand errorevent handlers receive the same arguments that you would receive from the corresponding events of the jQueryajaxmethod.

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

回答by Tarion

I got the following for me:

我得到了以下内容:

formSubmit('#login-form', '/api/user/login', '/members/');

where

在哪里

function formSubmit(form, url, target) {
    $(form).submit(function(event) {
        $.post(url, $(form).serialize())
            .done(function(res) {
                if (res.success) {
                    window.location = target;
                }
                else {
                    alert(res.error);
                }
            })
            .fail(function(res) {
                alert("Server Error: " + res.status + " " + res.statusText);

            })
        event.preventDefault();
    });
}

This assumes the post to 'url' returns an ajax in the form of {success: false, error:'my Error to display'}

这假设“url”的帖子以以下形式返回一个ajax {success: false, error:'my Error to display'}

You can vary this as you like. Feel free to use that snippet.

你可以随心所欲地改变它。随意使用该片段。

回答by jeet singh parmar

jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button

jQuery AJAX 提交表单,只不过是在单击按钮时使用表单 ID 提交表单

Please follow steps

请按照步骤

Step 1 - Form tag must have an ID field

第 1 步 - 表单标签必须有一个 ID 字段

<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>

Button which you are going to click

您要单击的按钮

<button>Save</button>

Step 2 - submitevent is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.

第 2 步 -提交事件在 jQuery 中,它有助于提交表单。在下面的代码中,我们正在准备来自 HTML 元素名称的JSON 请求。

$("#submitForm").submit(function(e) {
    e.preventDefault();
    var frm = $("#submitForm");
    var data = {};
    $.each(this, function(i, v){
        var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });
    $.ajax({
        contentType:"application/json; charset=utf-8",
        type:frm.attr("method"),
        url:frm.attr("action"),
        dataType:'json',
        data:JSON.stringify(data),
        success:function(data) {
            alert(data.message);
        }
    });
});

for live demo click on below link

现场演示点击下面的链接

How to submit a Form using jQuery AJAX?

如何使用 jQuery AJAX 提交表单?