Send POST data using XMLHttpRequest

前端 未结 13 1417
说谎
说谎 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:48

    There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate

    http.open('POST', url, true);
    http.send('lorem=ipsum&name=binny');
    

    I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()

    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    

    If you're using JSON and not URL-encoded data, pass application/json instead

    0 讨论(0)
  • 2020-11-21 04:49

    I have faced similar problem, using the same post and and this link I have resolved my issue.

     var http = new XMLHttpRequest();
     var url = "MY_URL.Com/login.aspx";
     var params = 'eid=' +userEmailId+'&amp;pwd='+userPwd
    
     http.open("POST", url, true);
    
     // Send the proper header information along with the request
     //http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     //http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
     //http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
    
     // Call a function when the state 
     http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
     }
     http.send(params);
    

    This link has completed information.

    0 讨论(0)
  • 2020-11-21 04:50

    The code below demonstrates on how to do this.

    var http = new XMLHttpRequest();
    var url = 'get_data.php';
    var params = 'orem=ipsum&name=binny';
    http.open('POST', url, true);
    
    //Send the proper header information along with the request
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(params);
    

    In case you have/create an object you can turn it into params using the following code, i.e:

    var params = new Object();
    params.myparam1 = myval1;
    params.myparam2 = myval2;
    
    // Turn the data object into an array of URL-encoded key/value pairs.
    let urlEncodedData = "", urlEncodedDataPairs = [], name;
    for( name in params ) {
     urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
    }
    
    0 讨论(0)
  • 2020-11-21 04:52

    Just for feature readers finding this question. I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE. Here is what I came up with:

    function post(path, data, callback) {
        "use strict";
        var request = new XMLHttpRequest();
    
        if (path === "") {
            path = "/";
        }
        request.open('POST', path, true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        request.onload = function (d) {
            callback(d.currentTarget.response);
        };
        request.send(serialize(data));
    }
    

    You can you it like so:

    post("", {orem: ipsum, name: binny}, function (response) {
        console.log(respone);
    })
    
    0 讨论(0)
  • 2020-11-21 04:53

    Here is a complete solution with application-json:

    // Input values will be grabbed by ID
    <input id="loginEmail" type="text" name="email" placeholder="Email">
    <input id="loginPassword" type="password" name="password" placeholder="Password">
    
    // return stops normal action and runs login()
    <button onclick="return login()">Submit</button>
    
    <script>
        function login() {
            // Form fields, see IDs above
            const params = {
                email: document.querySelector('#loginEmail').value,
                password: document.querySelector('#loginPassword').value
            }
    
            const http = new XMLHttpRequest()
            http.open('POST', '/login')
            http.setRequestHeader('Content-type', 'application/json')
            http.send(JSON.stringify(params)) // Make sure to stringify
            http.onload = function() {
                // Do whatever with response
                alert(http.responseText)
            }
        }
    </script>
    

    Ensure that your Backend API can parse JSON.

    For example, in Express JS:

    import bodyParser from 'body-parser'
    app.use(bodyParser.json())
    
    0 讨论(0)
  • 2020-11-21 04:54

    Short & modern

    You can catch form input values using FormData and send them by fetch

    fetch(form.action, {method:'post', body: new FormData(form)});
    

    function send() {
      let form = document.forms['inputform'];
      fetch(form.action, {method:'post', body: new FormData(form)});
    }
    <form name="inputform" action="somewhere" method="post">
      <input               value="person" name="user">
      <input type="hidden" value="password" name="pwd">
      <input               value="place" name="organization">
      <input type="hidden" value="key" name="requiredkey">
    </form>
    
    <!-- I remove type="hidden" for some inputs above only for show them --><br>
    Look: chrome console>network and click <button onclick="send()">send</button>

    0 讨论(0)
提交回复
热议问题