Send POST data using XMLHttpRequest

前端 未结 13 1475
说谎
说谎 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: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]));
    }
    

提交回复
热议问题