Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

javascript - AJAX XMLHttpRequest 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("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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, '+');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...