Send POST data using XMLHttpRequest

前端 未结 13 1419
说谎
说谎 2020-11-21 04:27

I\'d like to send some data using an XMLHttpRequest in JavaScript.

Say I have the following form in HTML:

<         


        
相关标签:
13条回答
  • 2020-11-21 04:55
    var util = {
        getAttribute: function (dom, attr) {
            if (dom.getAttribute !== undefined) {
                return dom.getAttribute(attr);
            } else if (dom[attr] !== undefined) {
                return dom[attr];
            } else {
                return null;
            }
        },
        addEvent: function (obj, evtName, func) {
            //Primero revisar attributos si existe o no.
            if (obj.addEventListener) {
                obj.addEventListener(evtName, func, false);
    
            } else if (obj.attachEvent) {
                obj.attachEvent(evtName, func);
            } else {
                if (this.getAttribute("on" + evtName) !== undefined) {
                    obj["on" + evtName] = func;
                } else {
                    obj[evtName] = func;
                }
    
            }
    
        },
        removeEvent: function (obj, evtName, func) {
            if (obj.removeEventListener) {
                obj.removeEventListener(evtName, func, false);
            } else if (obj.detachEvent) {
                obj.detachEvent(evtName, func);
            } else {
                if (this.getAttribute("on" + evtName) !== undefined) {
                    obj["on" + evtName] = null;
                } else {
                    obj[evtName] = null;
                }
            }
    
        },
        getAjaxObject: function () {
            var xhttp = null;
            //XDomainRequest
            if ("XMLHttpRequest" in window) {
                xhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhttp;
        }
    
    };
    
    //START CODE HERE.
    
    var xhr = util.getAjaxObject();
    
    var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
    
    if (isUpload) {
        util.addEvent(xhr, "progress", xhrEvt.onProgress());
        util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
        util.addEvent(xhr, "abort", xhrEvt.onAbort);
    }
    
    util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);
    
    var xhrEvt = {
        onProgress: function (e) {
            if (e.lengthComputable) {
                //Loaded bytes.
                var cLoaded = e.loaded;
            }
        },
        onLoadStart: function () {
        },
        onAbort: function () {
        },
        onReadyState: function () {
            var state = xhr.readyState;
            var httpStatus = xhr.status;
    
            if (state === 4 && httpStatus === 200) {
                //Completed success.
                var data = xhr.responseText;
            }
    
        }
    };
    //CONTINUE YOUR CODE HERE.
    xhr.open('POST', 'mypage.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    
    if ('FormData' in window) {
        var formData = new FormData();
        formData.append("user", "aaaaa");
        formData.append("pass", "bbbbb");
    
        xhr.send(formData);
    
    } else {
    
        xhr.send("?user=aaaaa&pass=bbbbb");
    }
    
    0 讨论(0)
  • 2020-11-21 04:57

    Use modern JavaScript!

    I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

    const url = "http://example.com";
    fetch(url, {
        method : "POST",
        body: new FormData(document.getElementById("inputform")),
        // -- or --
        // body : JSON.stringify({
            // user : document.getElementById('user').value,
            // ...
        // })
    }).then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );

    In Node.js, you'll need to import fetch using:

    const fetch = require("node-fetch");
    

    If you want to use it synchronously (doesn't work in top scope):

    const json = await fetch(url, optionalOptions)
      .then(response => response.json()) // .text(), etc.
      .catch((e) => {});
    

    More Info:

    Mozilla Documentation

    Can I Use (96% Nov 2020)

    David Walsh Tutorial

    0 讨论(0)
  • 2020-11-21 05:00

    Try to use json object instead of formdata. below is the code working for me. formdata doesnot work for me either, hence I came up with this solution.

    var jdata = new Object();
    jdata.level = levelVal; // level is key and levelVal is value
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://MyURL", true);
    xhttp.setRequestHeader('Content-Type', 'application/json');
    xhttp.send(JSON.stringify(jdata));
    
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          console.log(this.responseText);
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:03

    Minimal use of FormData to submit an AJAX request

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
    <script>
    "use strict";
    function submitForm(oFormElement)
    {
      var xhr = new XMLHttpRequest();
      xhr.onload = function(){ alert (xhr.responseText); } // success case
      xhr.onerror = function(){ alert (xhr.responseText); } // failure case
      xhr.open (oFormElement.method, oFormElement.action, true);
      xhr.send (new FormData (oFormElement));
      return false;
    }
    </script>
    </head>
    
    <body>
    <form method="post" action="somewhere" onsubmit="return submitForm(this);">
      <input type="hidden" value="person"   name="user" />
      <input type="hidden" value="password" name="pwd" />
      <input type="hidden" value="place"    name="organization" />
      <input type="hidden" value="key"      name="requiredkey" />
      <input type="submit" value="post request"/>
    </form>
    </body>
    </html>
    

    Remarks

    1. This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.

    2. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.

    3. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.

    0 讨论(0)
  • 2020-11-21 05:03

    This helped me as I wanted to use only xmlHttpRequest and post an object as form data:

    function sendData(data) {
      var XHR = new XMLHttpRequest();
      var FD  = new FormData();
    
      // Push our data into our FormData object
      for(name in data) {
        FD.append(name, data[name]);
      }
    
      // Set up our request
      XHR.open('POST', 'https://example.com/cors.php');
    
      // Send our FormData object; HTTP headers are set automatically
      XHR.send(FD);
    }
    

    https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

    0 讨论(0)
  • 2020-11-21 05:04
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'somewhere', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onload = function () {
        // do something to response
        console.log(this.responseText);
    };
    xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
    

    Or if you can count on browser support you could use FormData:

    var data = new FormData();
    data.append('user', 'person');
    data.append('pwd', 'password');
    data.append('organization', 'place');
    data.append('requiredkey', 'key');
    
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'somewhere', true);
    xhr.onload = function () {
        // do something to response
        console.log(this.responseText);
    };
    xhr.send(data);
    
    0 讨论(0)
提交回复
热议问题