xmlHttp string passing
the current xmlhttp function i am using is passing a very tiny int to the php file for processing using the GET method.
xmlhttp=GetXmlHttpObject();
if (xmlhttp开发者_Python百科==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="user_submit.php";
url=url+"?vote="+value;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("captionbox").innerHTML=xmlhttp.responseText;
}
}
now i want to process a comment
box in this ajax request, which i suppose would require a POST call? can anyone help me with this?
i need to send the contents of the comment box through this ajax request to the php file for processing and then adding into the DB.
...
var url="user_submit.php",
data="vote="+value+"&sid="+Math.random();
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
xmlHttp.setRequestHeader("Content-length", data.length);
xmlhttp.open("POST",url,true);
...
xmlHttp.send( data );
...
You use send()
to send POST data this way. You then have to send the right headers and encode that data correctly, etc.
That being said, it's incredibly tedious using XmlHttpRequest
. There are cross-browser issues to consider (eg fallbacks for when XmlHttpRequest
doesn't exist) and as you can see the code itself is messy.
Consider using a Javascript library like jQuery instead and then it reduces your code to:
$("#captionbox").load('user_submit.php', {
vote: value,
sid: 12345
});
which will also do the encoding of query string parameters (and many other things) correctly out of the box.
To post a comment, imagine you have:
<textarea id="comment"></textarea>
<input type="button" id="send" value="Send">
then:
$.post("post_comment.php", {
comment: $("#comment").text()
});
And jQuery is only 19K minified and gzipped.
精彩评论