JavaScript: How can I POST an arbitrary request body to a server?

こ雲淡風輕ζ 提交于 2021-01-01 06:24:57

问题


Normal, we can send an Ajax request or submit a form to a server, which in the HTTP request body would be encoded like this: name=helloworld&age=123.

Now our server only accepts JSON data as the request body. Is there a way to change the encoding method of the request body in JavaScript?


回答1:


HTML forms give you three options for encoding the data. text/plain is useful only for debugging (and not very useful even when given browser developer tools), and neither of the other two are JSON.

With XHR, the encoding is however you encode the data.

The send method can take a string: You can encode the data in that string however you like.

function sendJSON() {
    var data = {
        name: "helloworld",
        age: 123
    };

    var json = JSON.stringify(data);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/example/");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(json);
}

You can also pass other kinds of data such as a FormData object (which can include files and will us multipart encoding) but you don't need anything so complex for JSON.



来源:https://stackoverflow.com/questions/20661363/javascript-how-can-i-post-an-arbitrary-request-body-to-a-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!