duanaiguang1960
duanaiguang1960
2015-08-13 04:01
浏览 91

Ajax获取表单数据和URL

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.

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

Tutorial 1 does the follwoing:

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:

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.

  1. Where tutorial1 physically gets all the form fields i.e data:'userName='+$("#userName").val()+ tutorial2 simply does the following data: 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?

  1. Tutorial 1 hardcodes the url where tutorial2 gets the form and assign the action attribute to the 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?

  1. Which example/ tutorial is the better one in terms of best practice?

Thanks in advance

图片转代码服务由CSDN问答提供 功能建议

学习 AJAX通过以下在线教程并获得SO SO的帮助 社区卡住了。 我正在慢慢掌握它。

我的问题基于我正在关注的两个不同的教程

< em>教程1执行以下操作:

  jQuery.ajax({
 url:“contact_mail.php”,
 data:' 的userName = '+ $( “#的userName”)VAL()+' &安培; USEREMAIL = '+ $( “#USEREMAIL”)VAL()+' &安培受试者='+ $( “#主题”)。  val()+'&amp; content ='+ $(content).val(),
 type:“POST”,
 success:function(data){
 $(“#mail-status”)。html  (数据); 
},
错误:function(){} 
}); 
   
 
 

教程2执行以下操作 :

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

不幸的是,这两个教程都没有涵盖 url data < ajax调用中的/ code>属性,这就是我的问题所在。

  1. 其中tutorial1在物理上获取所有表单字段,即 data:'userName = '+ $(“#userName”)。val()+ tutorial2只执行以下数据:formData

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

    1. 教程1对 url 进行硬编码,其中tutorial2获取表单并将action属性分配给 url:$(form).attr(' 动作')

      因此,我说你不必对URL进行硬编码,而是从表单中获取并指定 属性操作到网址?

      1. 哪个示例/教程在最佳实践方面更好?

        提前致谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douti9253
    douti9253 2015-08-13 04:34
    已采纳

    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.

    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.

    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).

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

    点赞 评论
  • douzhi9395
    douzhi9395 2015-08-13 04:05
    1. $(form).serialize(); Basically does what is typed out in the first example for you automatically. See 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

    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

    点赞 评论
  • douman6245
    douman6245 2015-08-13 04:10

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

    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

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

    点赞 评论

相关推荐