Ajax获取表单数据和URL

时间:2022-10-13 15:14:02

I am learning AJAX by following some online tutorials and getting help from the very kind SO community when stuck. I am slowly getting the hang of it.

我正在通过一些在线教程学习AJAX,并在遇到困难的时候从非常友好的SO社区获得帮助。我正在慢慢掌握它。

My question is based on 2 different tutorials I am following for a contact form

我的问题基于我正在关注联系表单的2个不同的教程

Tutorial 1 does the follwoing:

教程1执行以下操作:

jQuery.ajax({
        url: "contact_mail.php",
        data:'userName='+$("#userName").val()+'&userEmail='+$("#userEmail").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
        type: "POST",
        success:function(data){
        $("#mail-status").html(data);
        },
        error:function (){}
        });

Tutorial 2 does the follwoing:

教程2执行以下操作:

var formData = $(form).serialize();
$.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

My question

Unfortunately both tutorials does not really cover the url and data attributes in the ajax call and this is where my question comes in.

不幸的是,这两个教程并没有真正涵盖ajax调用中的url和data属性,这就是我的问题所在。

  1. Where tutorial1 physically gets all the form fields i.e data:'userName='+$("#userName").val()+ tutorial2 simply does the following data: formData
  2. 其中tutorial1物理上获取所有表单字段,即data:'userName ='+ $(“#userName”)。val()+ tutorial2只执行以下数据:formData

Thus am I correct in saying that you do not physically have to get all the form fields like in tutorial1 but rather you can just get the whole form and assign it to a variable and send that as data?

因此,我是否正确地说你没有像在tutorial1中那样获得所有表单字段,而是你可以获得整个表单并将其分配给变量并将其作为数据发送?

  1. Tutorial 1 hardcodes the url where tutorial2 gets the form and assign the action attribute to the url: $(form).attr('action'),
  2. 教程1硬编码tutorial2获取表单的url,并将action属性分配给url:$(form).attr('action'),

Thus am I correct in saying that you do not have to hardcode the URL but rather get it from the form and assign the attribute action to the url?

因此,我是否正确地说您不必对URL进行硬编码,而是从表单中获取它并将属性操作分配给URL?

  1. Which example/ tutorial is the better one in terms of best practice?
  2. 哪个示例/教程在最佳实践方面更好?

Thanks in advance

提前致谢

3 个解决方案

#1


1  

To answer your first question, jQuery's .serialize() will take a given form or individual inputs/selects/etc. and produce a string of URL-encoded parameters to be sent via POST or GET. This is a very handy thing to do when working with forms. Tutorial 1 is effectively doing the same thing as tutorial 2 by manually constructing this string.

为了回答你的第一个问题,jQuery的.serialize()将采用给定的表单或单独的输入/选择/等。并生成一串URL编码的参数,通过POST或GET发送。在处理表单时,这是一件非常方便的事情。教程1通过手动构造此字符串有效地执行与教程2相同的操作。

Tutorial 2 seems preferable over Tutorial 1 here, as Tutorial 1 is far more repetitive and, as such, less maintainable and more error prone. However, a mixture of the two may sometimes be needed, as you may sometimes want to send additional data in the request that isn't in the form.

教程2似乎优于教程1,因为教程1更具重复性,因此可维护性更低,更容易出错。但是,有时可能需要两者的混合,因为有时您可能希望在请求中发送不在表单中的其他数据。

For your second question, it doesn't really make too much of a difference what you do here, but you'd probably be better off placing the URL in your markup rather than your code, since you'd typically generate URLs when using a typical Web Framework, and it's good practice to treat HTML as templates and JS/CSS as static assets (you wouldn't want to template your JavaScript with URLs).

对于你的第二个问题,你在这里做的并没有太大的区别,但你可能最好将URL放在你的标记而不是你的代码中,因为你通常在使用时生成URL典型的Web框架,将HTML视为模板,将JS / CSS视为静态资产是一种很好的做法(您不希望使用URL模板化JavaScript)。

However, this situation might be different if you were using a front-end framework like Angular or Ember.

但是,如果您使用的是Angular或Ember等前端框架,则这种情况可能会有所不同。

#2


2  

As per my view Tutorial2 is good because there he has written that particular ajax method in terms of General action i.e. you can have one single ajax function for submitting any number of forms. Say I have below ajax wrapped in a function()

根据我的观点,Tutorial2很好,因为他已经根据一般操作编写了特定的ajax方法,即你可以有一个单独的ajax函数来提交任意数量的表单。说我在ajax下面包含一个函数()

function submitForm(form){ //accepts form as parameter
    var formData = $(form).serialize(); //serialize this particular form
    $.ajax({
              type: 'POST',
              url: $(form).attr('action'), //get value from forms action attrbute
              data: formData
    }).done(function(response) {

    });
}

Now say I have 2 forms as below

现在说我有两种形式如下

<form id="frm1" action="Page1.html" onsubmit="submitForm(this)">
        .....    
</form>

<form id="frm2" action="Page2.html" onsubmit="submitForm(this)">
        .....    
</form>

Now from both the forms you are passing form itself as parameter to the function which the function manipulates using the js written above

现在,从你传递的两种形式作为参数传递给函数,函数使用上面写的js操作

Now the Tutorial1 might be just to understand for the starters what values should be there or how it works around.

现在,Tutorial1可能只是为初学者理解应该存在哪些值或它是如何工作的。

#3


1  

  1. $(form).serialize(); Basically does what is typed out in the first example for you automatically. See https://api.jquery.com/serialize/

    $(形式).serialize();基本上会自动为您在第一个示例中输入的内容。请参阅https://api.jquery.com/serialize/

  2. Yes you can set the url however you want, tutorial 2 uses the current forms action. You could set this via a variable or hardcode it depending on what your goal is. In this case since the tutorial is showing you how to submit a normal form via ajax they will always use the form they are submitting's action

    是的,您可以根据需要设置URL,教程2使用当前的表单操作。您可以通过变量或硬编码来设置它,具体取决于您的目标。在这种情况下,由于本教程向您展示了如何通过ajax提交普通表单,因此他们将始终使用他们提交动作的表单

  3. The second tutorial seems much cleaner but is for the specific case where you want to send a form via ajax not make a custom post

    第二个教程似乎更清晰,但是对于您想通过ajax发送表单而不是自定义帖子的特定情况

#1


1  

To answer your first question, jQuery's .serialize() will take a given form or individual inputs/selects/etc. and produce a string of URL-encoded parameters to be sent via POST or GET. This is a very handy thing to do when working with forms. Tutorial 1 is effectively doing the same thing as tutorial 2 by manually constructing this string.

为了回答你的第一个问题,jQuery的.serialize()将采用给定的表单或单独的输入/选择/等。并生成一串URL编码的参数,通过POST或GET发送。在处理表单时,这是一件非常方便的事情。教程1通过手动构造此字符串有效地执行与教程2相同的操作。

Tutorial 2 seems preferable over Tutorial 1 here, as Tutorial 1 is far more repetitive and, as such, less maintainable and more error prone. However, a mixture of the two may sometimes be needed, as you may sometimes want to send additional data in the request that isn't in the form.

教程2似乎优于教程1,因为教程1更具重复性,因此可维护性更低,更容易出错。但是,有时可能需要两者的混合,因为有时您可能希望在请求中发送不在表单中的其他数据。

For your second question, it doesn't really make too much of a difference what you do here, but you'd probably be better off placing the URL in your markup rather than your code, since you'd typically generate URLs when using a typical Web Framework, and it's good practice to treat HTML as templates and JS/CSS as static assets (you wouldn't want to template your JavaScript with URLs).

对于你的第二个问题,你在这里做的并没有太大的区别,但你可能最好将URL放在你的标记而不是你的代码中,因为你通常在使用时生成URL典型的Web框架,将HTML视为模板,将JS / CSS视为静态资产是一种很好的做法(您不希望使用URL模板化JavaScript)。

However, this situation might be different if you were using a front-end framework like Angular or Ember.

但是,如果您使用的是Angular或Ember等前端框架,则这种情况可能会有所不同。

#2


2  

As per my view Tutorial2 is good because there he has written that particular ajax method in terms of General action i.e. you can have one single ajax function for submitting any number of forms. Say I have below ajax wrapped in a function()

根据我的观点,Tutorial2很好,因为他已经根据一般操作编写了特定的ajax方法,即你可以有一个单独的ajax函数来提交任意数量的表单。说我在ajax下面包含一个函数()

function submitForm(form){ //accepts form as parameter
    var formData = $(form).serialize(); //serialize this particular form
    $.ajax({
              type: 'POST',
              url: $(form).attr('action'), //get value from forms action attrbute
              data: formData
    }).done(function(response) {

    });
}

Now say I have 2 forms as below

现在说我有两种形式如下

<form id="frm1" action="Page1.html" onsubmit="submitForm(this)">
        .....    
</form>

<form id="frm2" action="Page2.html" onsubmit="submitForm(this)">
        .....    
</form>

Now from both the forms you are passing form itself as parameter to the function which the function manipulates using the js written above

现在,从你传递的两种形式作为参数传递给函数,函数使用上面写的js操作

Now the Tutorial1 might be just to understand for the starters what values should be there or how it works around.

现在,Tutorial1可能只是为初学者理解应该存在哪些值或它是如何工作的。

#3


1  

  1. $(form).serialize(); Basically does what is typed out in the first example for you automatically. See https://api.jquery.com/serialize/

    $(形式).serialize();基本上会自动为您在第一个示例中输入的内容。请参阅https://api.jquery.com/serialize/

  2. Yes you can set the url however you want, tutorial 2 uses the current forms action. You could set this via a variable or hardcode it depending on what your goal is. In this case since the tutorial is showing you how to submit a normal form via ajax they will always use the form they are submitting's action

    是的,您可以根据需要设置URL,教程2使用当前的表单操作。您可以通过变量或硬编码来设置它,具体取决于您的目标。在这种情况下,由于本教程向您展示了如何通过ajax提交普通表单,因此他们将始终使用他们提交动作的表单

  3. The second tutorial seems much cleaner but is for the specific case where you want to send a form via ajax not make a custom post

    第二个教程似乎更清晰,但是对于您想通过ajax发送表单而不是自定义帖子的特定情况