Simple ajax form using javascript no jQuery

前端 未结 9 1018
终归单人心
终归单人心 2020-11-28 11:46

I\'m working with a form for which the mark-up I can\'t change & can\'t use jQuery. Currently the form post the results to a new window. Is it possible to change this to

相关标签:
9条回答
  • 2020-11-28 12:41

    A modern way using fetch would be:

    const formData = new FormData(form);
    fetch(form.action, {
      method: 'POST',
      body: formData
    });
    

    Note browser support and use this polyfil if IE-support is needed

    0 讨论(0)
  • 2020-11-28 12:41
    function ajaxSubmit(form, callback) {
    var xhr = new XMLHttpRequest();
    var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
    .filter(function(el) { return !!el.name; }) //Nameless elements die.
    .filter(function(el) { return !el.disabled; }) //Disabled elements die.
    .map(function(el) {
        if (el.type=='checkbox') return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.checked);
       else return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
    }).join('&'); //Then join all the strings by &
    xhr.open("POST", form.action);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onload = callback.bind(xhr);
    xhr.send(params);
    

    };

    0 讨论(0)
  • 2020-11-28 12:46

    Here's the simplest method I came up with. I haven't found an example that uses this exact approach. The code submits the form using a non-submit type button and places the results into a div, if the form is not valid (not all required fields filled), it will ignore the submit action and the browser itself will show which fields are not filled correctly.

    This code only works on modern browsers supporting the "FormData" object.

    <script>
    function ajaxSubmitForm() {
      const form = document.getElementById( "MyForm" );
      if (form.reportValidity()) {
        const FD = new FormData( form );
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("content_area").innerHTML = this.responseText; } };
        xhttp.open("POST","https://example.com/whatever.php",true);
        xhttp.send( FD );
      }
    }
    </script>
    
    <div id="content_area">
    <form id="MyForm">
      <input type="hidden" name="Token" Value="abcdefg">
      <input type="text" name="UserName" Value="John Smith" required>
      <input type="file" accept="image/jpeg" id="image_uploads" name="ImageUpload" required>
      <button type="button" onclick="ajaxSubmitForm()">
    </form>
    </div>
    
    0 讨论(0)
提交回复
热议问题