I wrote the Ajax function like below.
It is not working properly. If I remove the xmlhttp.status==400
then it is working. What mistake have I made in this example?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function getAjax()
{
if (window.XMLHTTPRequest)
{
xmlhttp=new XMLHTTPRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.xmlHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==400)
{
document.getElementById('mydiv').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","testajax.txt",true);
xmlhttp.send(null);
}
</script>
</head>
<body>
开发者_如何转开发 <input type="button" value="Get content" onclick="getAjax()"><br>
<div id="mydiv"></div>
</body>
</html>
"Another simple use is finding if a url exists, in HTTP there are various status codes returned by both HEAD and GET requests, 200 means success, 404 means failure, and the others mean other things. See HTTP status codes for a full explanation."
using the status property of the xmlhttp object provides you this status
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) alert("URL Exists!")
else if (xmlhttp.status==404) alert("URL doesn't exist!")
}
http://www.jibbering.com/2002/4/httprequest.2004.9.html
Change 400
to 200
. That's an HTTP status code. 200
means OK
. 400
means Bad Request
.
The proper "if
" condition should have been:-
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('mydiv').innerHTML=xmlhttp.responseText;
}
For more deeper understanding, you can see this nice & detailed article from IBM Technical Library's Mastering AJAX. Also, you could have easily used the jQuery.ajax() API of the jQuery library.
Hope it helps.
精彩评论