Send POST data using XMLHttpRequest

前端 未结 13 1428
说谎
说谎 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 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);
    

提交回复
热议问题