JavaScript:如何将任意请求正文发布到服务器? [英] JavaScript: How can I POST an arbitrary request body to a server?

查看:43
本文介绍了JavaScript:如何将任意请求正文发布到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正常情况下,我们可以发送Ajax请求或向服务器提交表单,该表单在 HTTP请求正文中的编码如下: name = helloworld& age = 123 .

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.

现在我们的服务器仅接受JSON数据作为请求正文.有没有办法在JavaScript中更改请求主体的编码方法?

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?

推荐答案

HTML表单为您提供了三种用于编码数据的选项. text/plain 仅对调试有用(即使使用给定的浏览器开发人员工具也不太有用),另外两个都不是JSON.

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.

使用 XHR 时,您可以对编码进行编码数据.

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

send 方法可以使用一个字符串:您可以根据需要在该字符串中编码数据.

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);
}

您还可以传递其他类型的数据,例如 FormData 对象(可以包含文件,并且可以进行多部分编码),但是对于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.

这篇关于JavaScript:如何将任意请求正文发布到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆