Javascript AJAX XMLHttpRequest POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4276226/
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 11:41:19  来源:igfitidea点击:

AJAX XMLHttpRequest POST

javascriptajaxpostxmlhttprequest

提问by diggersworld

I'm trying to write an XMLHttpRequest using the POST method. I have managed to use XMLHttpRequest in the past using the GET method but am struggling with POST.

我正在尝试使用 POST 方法编写 XMLHttpRequest。我过去曾使用 GET 方法设法使用 XMLHttpRequest,但在使用 POST 时遇到了困难。

Here's my code:

这是我的代码:

var xmlhttp = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

var url = "http://www.mysite.com/script.php";
var params = "var=1";
xmlhttp.open("POST", url, true);
xmlhttp.send(params);

It basically calls a PHP script which then adds some information to a database.

它基本上调用一个 PHP 脚本,然后将一些信息添加到数据库中。

采纳答案by diggersworld

Okay I've managed to sort it.

好的,我已经设法对其进行了排序。

Odd reason though, might be sandbox security related, but rather than have the full URL address, I have just used the relative path to the file, and now it works.

奇怪的原因可能与沙箱安全相关,但我没有使用完整的 URL 地址,而是使用了文件的相对路径,现在它可以工作了。

Thank you all for your support.

谢谢大家的支持。

回答by Marcel Korpel

You forgot to explicitly set to Content-typeheader, which is necessary when doing POST requests.

您忘记显式设置为Content-typeheader,这在执行 POST 请求时是必需的。

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Also, do not forget to use encodeURIComponentto properly encode your parameters, e.g.:

另外,不要忘记使用encodeURIComponent正确编码您的参数,例如:

var params = "var=" + encodeURIComponent("1");

(in this particular example, it's not necessary, but when using special characters like +things will go horribly wrong if you don't encode the parameter text).

(在这个特定的例子中,这是没有必要的,但是当使用特殊字符时,+如果你不对参数文本进行编码,事情会发生可怕的错误)。

Update– you should also replace all instances of %20with +, like

更新- 您还应该替换%20with 的所有实例+,例如

var params = params.replace(/%20/g, '+');