Send POST data using XMLHttpRequest

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

提交回复
热议问题