To create your first Ajax program, use a non-synchronous method to obtain a Text Example from the servo end, and provide instructions. First, please download an HTML webpage:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Meta content = "text/html; charset = big5" http-equiv = "Content-Type">
<Title> hello! Ajax! Examples... </title>
<SCRIPT type = "text/JavaScript" src = "HelloAjaxEx-1.js"> </SCRIPT>
</Head>
<Body>
<Center> <input value = "ajax" onclick = "startrequest ();" type = "button"> </center>
</Body>
</Html>
This html website will obtain the Javascript attack case, and after pressing the button, it will write the startrequest () function. The javascript attack case is 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-1.txt ");
XMLHTTP. Send (null );
}
Function handlestatechange (){
If (XMLHTTP. readystate = 4 ){
If (XMLHTTP. Status = 200 ){
Alert ("servo response:" + XMLHTTP. responsetext );
}
}
}
Refer to the following example:
This is a non-Synchronous Response text.
You can press the response to see the result.
You can combine the Dom to display the response text, without the need to use the caller or refresh website, for example, set a <div> In the webpage:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Meta content = "text/html; charset = big5" http-equiv = "Content-Type">
<Title> hello! Ajax! Examples... </title>
<SCRIPT type = "text/JavaScript" src = "HelloAjaxEx-2.js"> </SCRIPT>
</Head>
<Body>
<Center>
<Input value = "ajax request" onclick = "startrequest ();" type = "button">
<Br>
<Div id = "response"> </div>
</Center>
</Body>
</Html>
And the HelloAjaxEx-2.js can be modified 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;
}
}
}
In this example, the innerhtml encoding of DOM objects is used directly. You can view the result by following the results.