AJAX XMLHttpRequest POST

dig*_*rld 14 javascript ajax post xmlhttprequest

我正在尝试使用POST方法编写XMLHttpRequest.我过去曾使用GET方法设法使用XMLHttpRequest,但我正在努力使用POST.

这是我的代码:

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);
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*pel 49

您忘记显式设置为Content-type标头,这在执行POST请求时是必需的.

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Run Code Online (Sandbox Code Playgroud)

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

var params = "var=" + encodeURIComponent("1");
Run Code Online (Sandbox Code Playgroud)

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

更新 -你也应该替换的所有实例%20+,像

var params = params.replace(/%20/g, '+');
Run Code Online (Sandbox Code Playgroud)


dig*_*rld -6

好吧,我已经成功排序了。

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

感谢大家的支持。