Ajax to write your first AJAX program, use the asynchronous way to get text files to the server, and to display, first please prepare an HTML Web page:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<meta content= "text/html; Charset=big5 "http-equiv=" Content-type ">
<title>hello! Ajax! Examples...</title>
<script type= "Text/javascript" src= "Helloajaxex-1.js" ></script>
<body>
<center><input value= "Ajax Please" type= "button" ></center>
</body>
This HTML page will get the JavaScript file, and then press the button to perform the Startrequest () function, as the JavaScript file looks like this:
var xmlHttp;
function Createxmlhttprequest () {
if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
else if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
}
function Startrequest () {
Createxmlhttprequest ();
Xmlhttp.onreadystatechange = Handlestatechange;
Xmlhttp.open ("Get", "helloajaxex-1.txt");
Xmlhttp.send (NULL);
}
function Handlestatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
Alert ("Servo-response:" + Xmlhttp.responsetext);
}
}
}
In Startrequest () a xmlhttprequest is established, And out of sync please get helloajaxex-1.txt, which is simply a text message, and note that if you want to write Chinese, the text file must be stored as UTF8, and the HelloAjaxEx1.txt is written as follows:
This is a sync request response text
You can click on the link to see the results.
You can combine the DOM to display the response text you have obtained without using the conversation cube or the Refresh page, such as setting up a <div> in the Web:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<meta content= "text/html; Charset=big5 "http-equiv=" Content-type ">
<title>hello! Ajax! Examples...</title>
<script type= "Text/javascript" src= "Helloajaxex-2.js" ></script>
<body>
<center>
<input value= "Ajax Please" type= "button" >
<br>
<div id= "Response" ></div>
</center>
</body>
And helloajaxex-2.js can be changed as follows:
var xmlHttp;
function Createxmlhttprequest () {
if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
else if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
}
function Startrequest () {
Createxmlhttprequest ();
Xmlhttp.onreadystatechange = Handlestatechange;
Xmlhttp.open ("Get", "helloajaxex-2.txt");
Xmlhttp.send (NULL);
}
function Handlestatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
document.getElementById ("Response"). InnerHTML =
Xmlhttp.responsetext;
}
}
}
Here's a simple example of using the innerHTML of a DOM object, and you can see the results by the link.