Javascript 在Javascript中通过Rest API发送Http POST请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30976705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:01:14  来源:igfitidea点击:

Sending Http POST Request through Rest API in Javascript

javascriptjsonpostparse-platform

提问by Amir

I am trying to send an Http post request to parse.com server through Rest API keys. Not sure if I am doing it right as below. The following is my whole script and makes a button which should trigger the post request in a simple HTML page.

我正在尝试通过 Rest API 密钥向 parse.com 服务器发送 Http post 请求。不知道我是否按照下面的方式做对了。以下是我的整个脚本,并制作了一个按钮,该按钮应该在一个简单的 HTML 页面中触发发布请求。

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
<script>

xmlhttp = new XMLHttpRequest();
var url = "https://api.parse.com/1/classes/english";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("X-Parse-Application-Id", "VnxVYV8ndyp6hE7FlPxBdXdhxTCmxX1111111");
xmlhttp.setRequestHeader("X-Parse-REST-API-Key","6QzJ0FRSPIhXbEziFFPs7JvH1l11111111");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
var parameters = {
    "ephrase": "english",
    "pphrase": "farsi",
     "nvote": 0,
    "yvote": 0
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that

function doFunction() {
  xmlhttp.send(parameters);
}

</script>

回答by Quentin

xmlhttp.send(parameters);
             ^^^^^^^^^^

That needs to be a string, but it is an object, so will be converted to the string: "[object Object]".

那需要是一个字符串,但它是一个对象,所以将被转换为字符串:"[object Object]"

You need to convert the data to the proper encoding first.

您需要先将数据转换为正确的编码。

You've said:

你说过:

xmlhttp.setRequestHeader("Content-type", "application/json");

so you can use JSON.stringify(parameters)for that.

所以你可以使用JSON.stringify(parameters)它。