碜您第一Ajax程式,使用非同步的方式向伺服端取得文字n案,K加以@示,首先湟htmlW:
- HelloAjaxEx-1.html
<!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求" type="button"></center>
</body>
</html>
@HTMLW〉JavaScriptn案,而按下按o後,绦startRequest()函式,javaScriptn案如下所示:
- HelloAjaxEx-1.html
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("伺服端回" + xmlHttp.responseText);
}
}
}
在startRequest()中XMLHttpRequest,Kl出非同步求取得HelloAjaxEx-1.txt,在中只是蔚奈淖钟息,注意如果中要撰中文,t文字n案必ΥUTF8,假OHelloAjaxEx1.txt如下撰:
- HelloAjaxEx1.txt
@是非同步求的回淖
您可以按下 Y 碛^看Y果。
您可以Y合DOM盹@示取得的回淖郑槐厥褂υ方K或重清(Refresh)W,例如在W中O定一<div>:
- HelloAjaxEx-2.html
<!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求" type="button">
<br>
<div id="response"></div>
</center>
</body>
</html>
而HelloAjaxEx-2.js可以改如下:
- HelloAjaxEx-2.js
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;
}
}
}
在@榱撕化例,直接使用DOM物件的innerHTML傩裕梢园 Y ^看Y果。
欢迎大家阅读《llo! Ajax!_jquery》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码