dozc1071
dozc1071
采纳率100%
2014-02-09 18:06 阅读 61

使用ajax发送表单数据

I want to send all input in a form with ajax .I have a form like this.

<form action="target.php" method="post" >
    <input type="text" name="lname" />
    <input type="text" name="fname" />
    <input type="buttom" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>

And in .js file we have following code :

function f (form ,fname ,lname ){
    att=form.attr("action") ;
    $.post(att ,{fname : fname , lname :lname}).done(function(data){
        alert(data);
    });
    return true;

But this is not working.i don't want to use Form data .

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

7条回答 默认 最新

  • 已采纳
    douzhang1852 douzhang1852 2014-02-09 18:14

    as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:

    First Solution

    function submitForm(form){
        var url = form.attr("action");
        var formData = {};
        $(form).find("input[name]").each(function (index, node) {
            formData[node.name] = node.value;
        });
        $.post(url, formData).done(function (data) {
            alert(data);
        });
    }
    

    Second Solution: in this solution you can create an array of input values:

    function submitForm(form){
        var url = form.attr("action");
        var formData = $(form).serializeArray();
        $.post(url, formData).done(function (data) {
            alert(data);
        });
    }
    
    点赞 评论 复制链接分享
  • douzou0073 douzou0073 2014-02-09 18:09
    $.ajax({
      url: "target.php",
      type: "post",
      data: "fname="+fname+"&lname="+lname,
    }).done(function(data) {
      alert(data);
    });
    
    点赞 评论 复制链接分享
  • dsa1234569 dsa1234569 2014-02-09 18:10

    can you try this :

    function f (){
    fname  = $("input[name='fname']").val();
    lname  = $("input[name='fname']").val();
    att=form.attr("action") ;
    $.post(att ,{fname : fname , lname :lname}).done(function(data){
    alert(data);
    });
    return true;
    }
    
    点赞 评论 复制链接分享
  • dty9731 dty9731 2014-02-09 18:14

    In your function form is a DOM object, In order to use attr() you need to convert it to jQuery object.

    function f(form, fname, lname) {
        action = $(form).attr("action");
        $.post(att, {fname : fname , lname :lname}).done(function (data) {
            alert(data);
        });
        return true;
    }
    

    With .serialize()

    function f(form, fname, lname) {
        action = $(form).attr("action");
        $.post(att, $(form).serialize() ).done(function (data) {
            alert(data);
        });
        return true;
    }
    

    Additionally, You can use .serialize()

    点赞 评论 复制链接分享
  • doujie7346 doujie7346 2014-02-09 18:17

    I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
    Following part of the function might be of interest:

      if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
        //Get all the input elements in form
        var elem = data.elements;
        //Loop through the element array
        for(var i = 0; i < elem.length; i++) {
          //Ignore elements that are not supposed to be sent
          if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
            continue; 
          //Add & to any subsequent entries (that means every iteration except the first one) 
          if(data_string.length>0)
            data_string+="&";
          //Get data for selectbox
          if (elem[i].tagName.toUpperCase() == "SELECT")
          {
            data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
          }
          //Get data from checkbox
          else if(elem[i].type=="checkbox")
          {
            data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
          }
          //Get data from textfield
          else
          {
            data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
          }
        }
        return data_string; 
      }
    

    It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

    Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

    function ajax_create_request_string(data, recursion) {
      var data_string = '';
      //Zpracovani formulare
      if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
        //Get all the input elements in form
        var elem = data.elements;
        //Loop through the element array
        for(var i = 0; i < elem.length; i++) {
          //Ignore elements that are not supposed to be sent
          if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
            continue; 
          //Add & to any subsequent entries (that means every iteration except the first one) 
          if(data_string.length>0)
            data_string+="&";
          //Get data for selectbox
          if (elem[i].tagName.toUpperCase() == "SELECT")
          {
            data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
          }
          //Get data from checkbox
          else if(elem[i].type=="checkbox")
          {
            data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
          }
          //Get data from textfield
          else
          {
            if(elem[i].className.indexOf("autoempty")!=-1) {
              data_string += elem[i].name+"=";
            }
            else
              data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
          }
        }
        return data_string; 
      }
      //Loop through array
      if(data instanceof Array) {
        for(var i=0; i<data.length; i++) {
          if(data_string!="")
            data_string+="&";
          data_string+=recursion+"["+i+"]="+data[i];
        }
        return data_string;
      }
      //Loop through object (like foreach)
      for(var i in data) {
        if(data_string!="")
          data_string+="&";
        if(typeof data[i]=="object") {
          if(recursion==null)
            data_string+= ajax_create_request_string(data[i], i);
          else
            data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
        }
        else if(recursion==null)
          data_string+=i+"="+data[i];
        else 
          data_string+=recursion+"["+i+"]="+data[i];
      }
      return data_string;
    }
    
    点赞 评论 复制链接分享
  • doudou3935 doudou3935 2014-02-09 18:19

    you can use serialize method of jquery to get form values. Try like this

    <form action="target.php" method="post" >
    <input type="text" name="lname" />
    <input type="text" name="fname" />
    <input type="buttom" name ="send" onclick="return f(this.form) " >
    </form>
    
    function f( form ){
        var formData = $(form).serialize();
        att=form.attr("action") ;
        $.post(att, formData).done(function(data){
            alert(data);
        });
        return true;
    }
    
    点赞 评论 复制链接分享
  • dongmi19720408 dongmi19720408 2014-02-09 18:33

    The code you've posted has two problems:

    First: <input type="buttom" should be <input type="button".... This probably is just a typo but without button your input will be treated as type="text" as the default input type is text.

    Second: In your function f() definition, you are using the form parameter thinking it's already a jQuery object by using form.attr("action"). Then similarly in the $.post method call, you're passing fname and lname which are HTMLInputElements. I believe what you want is form's action url and input element's values.

    Try with the following changes:

    HTML

    <form action="/echo/json/" method="post">
        <input type="text" name="lname" />
        <input type="text" name="fname" />
    
        <!-- change "buttom" to "button" -->
        <input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
    </form>
    

    JavaScript

    function f(form, fname, lname) {
        att = form.action; // Use form.action
        $.post(att, {
            fname: fname.value, // Use fname.value
            lname: lname.value // Use lname.value
        }).done(function (data) {
            alert(data);
        });
        return true;
    }
    

    Here is the fiddle.

    点赞 评论 复制链接分享

相关推荐