form serialize javascript (no framework)

后端 未结 23 1550
一生所求
一生所求 2020-11-22 16:07

Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialized version?

23条回答
  •  旧时难觅i
    2020-11-22 16:45

      // supports IE8 and IE9 
      function serialize(form) {
        var inputs = form.elements;
        var array = [];
        for(i=0; i < inputs.length; i++) {
          var inputNameValue = inputs[i].name + '=' + inputs[i].value;
          array.push(inputNameValue);
        }
        return array.join('&');
      }
     //using the serialize function written above
     var form = document.getElementById("form");//get the id of your form. i am assuming the id to be named form.
     var form_data = serialize(form);
     var xhr = new XMLHttpRequest();
     xhr.send(form_data);
    
     //does not work with IE8 AND IE9
     var form = document.querySelector('form');
     var data = new FormData(form);
     var xhr = new XMLHttpRequest();
     xhr.send(data);
    

提交回复
热议问题