开发者

AJAX XMLHttpRequest POST

开发者 https://www.devze.com 2023-01-27 02:43 出处:网络
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.

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.

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("Mic开发者_开发知识库rosoft.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.


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

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

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

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 %20 with +, like

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


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.

Thank you all for your support.

0

精彩评论

暂无评论...
验证码 换一张
取 消