Ajax function call

I wrote an Ajax function as shown below.

It does not work properly. If I remove xmlhttp.status==400 then it will work. What mistake did I make 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> 
+4
source share
3 answers

"Another simple use is to find if a URL exists, HTTP has various status codes returned by both HEAD and GET requests, 200 means success, 404 means failure, and others are different. See HTTP status codes for full explanation. "

using the status property of an xmlhttp object, you provide 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

+1
source

The correct if condition must be: -

 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById('mydiv').innerHTML=xmlhttp.responseText; } 

For a deeper understanding, you can see this nice and detailed article in the IBM Technical Library AJAX Mastering . Alternatively, you could easily use the jQuery.ajax () jQuery API.

Hope this helps.

0
source

Change 400 to 200 . This is an HTTP status code . 200 means OK . 400 means Bad Request .

0
source

Source: https://habr.com/ru/post/1332180/


All Articles