In recent years, I have written too much JQuery. I haven't written traditional javascript for a long time. I have forgotten a lot of things. How many people still remember that implementing ajax operations in javascript requires the help of XMLHttpRequest object. In fact, this is the essence of ajax in jquery. OK Today I will take some time to demonstrate how to use traditional javascript to obtain text content and display it on the page. There is not much nonsense, just put the code directly on the code, and the comments are written in detail, so everyone should be able to understand:
The code copy is as follows:
<script type="text/javascript">
//(A)① Method for obtaining text file (traditional javascript implements AJAX writing method)
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 a function (or function name), which will be called whenever the readyState property changes.
xmlhttp.onreadystatechange=function()
{
//readyState
//The status of XMLHttpRequest is present. Changes from 0 to 4.
//0: The request is not initialized
//1: Server connection has been established
//2: The request has been received
//3: Request processing is underway
//4: The request has been completed 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:
The code copy is as follows:
<body>
<form id="form1" runat="server">
<%-- Get the text file on the server and display --%>
<div id="myDiv1"><h2>Change content through ajax</h2></div>
<button id="btnChange1" type="button" onclick="LoadXMLDoc1()">Change content through AJAX (get the text above test1.txt)</button>
</form>
</body>
Demonstration effect: