JavaScript calls ajax to get the text file content implementation code

  • 2020-03-30 02:29:13
  • OfStack

JQuery to write more for these years, the traditional javascript has not been written for a long time, many things are forgotten, how many people remember to implement ajax javascript operations require using the XMLHttpRequest object, in fact the JQuery ajax nature is also this, ok, today will take time to demonstrate how to use the traditional javascript get the text contents and displayed on the page, what nonsense not, directly on the code, comments write very detailed, you should be able to understand:
 
<script type="text/javascript"> 
//(A) get text file method (traditional javascript AJAX writing)
function LoadXMLDoc1() 
{ 
var xmlhttp; 
if(window.XMLHttpRequest) 
{ 
// code for IE7+, Firefox, Chrome, Opera, Safari 
xmlhttp=new XMLHttpRequest(); 
} 
else 
{ 
// code for IE6, IE5 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
//Onreadystatechange stores the function (or function name), which is called whenever the readyState property changes.
xmlhttp.onreadystatechange=function() 
{ 
//readyState 
//The state of XMLHttpRequest exists. It goes from 0 to 4.
//0: the request is not initialized
//1: server connection established
//2: request received
//3: the request is being processed
//4: the request is complete and the response is ready
//status 
//200: "OK" 
//404: page not found
if (xmlhttp.readyState==4 && xmlhttp.status==200) 
{ 
document.getElementById("myDiv1").innerHTML=xmlhttp.responseText; 
} 
} 
xmlhttp.open("GET","doc/test1.txt",true); 
xmlhttp.send(); 
} 

HTML page code:
 
<body> 
<form id="form1" runat="server"> 
<%--  Gets the text file on the server and displays it --%> 
<div id="myDiv1"><h2> through ajax Change the content </h2></div> 
<button id="btnChange1" type="button" onclick="LoadXMLDoc1()"> through  AJAX  Change the content ( To obtain test1.txt The text above )</button> 
</form> 
</body> 

Demonstration effect:
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201403/20140328144459.gif? 2014228144542 ">

Related articles: