這段時間在學習ajax,前今天給公司同事講解了一下基本原理,也隨便放在網上給大家參考一下。
我認為ajax簡單的講就是客戶端通過javascript腳本獲取服務器端的文本,通過解析返回值,更新部分的網頁內容。
下面結合一個獲取qq天氣預報網頁,并且對返回值進行處理的例子進行一下講解。
行數:解釋。
14:點擊按鈕開始獲取。
29:顯示右上角的“正在加載...”的小區域(仿造gmail)。
30:創建xmlhttp,ie的方式,其它的瀏覽器創建方式不同。
31:xmlhttp狀態發生變化時調用的回調函數,實現異步調用。
32:指定調用的url。
33:開始調用(可以發送一段xml到服務器端,例子可以查看:用javascript通過metaweblog獲取blog )。
37:xmlhttp的狀態:1 裝備階段、2 發送、3 接收、4 所有數據接收完成。
40:隱藏右上角提示。
41:服務器返回的狀態:200 正常返回。 404 網頁不存在 等。
45:以html格式顯示獲得的網頁。
46:以文本方式顯示獲得網頁源代碼。
49-53:截取部分網頁顯示。
58-60:沒有正常獲取網頁的提示。
----------------------
代碼下載:weather.zip
1<html>
2<head>
3<title> 天氣預報 </title>
4<meta name="author" content="http://pharaoh.cnblogs.com">
5</head>
6<body>
7 <!--
8 xmlhttp 說明
9 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/7924f6be-c035-411f-acd2-79de7a711b38.asp
10 -->
11<div id=load >正在加載</div>
12
13<input id=wurl value="http://appnews.qq.com/cgi-bin/news_qq_search?city=重慶">
14<button >加載</button>
15
16<hr />
17<div id=city>片斷</div>
18<hr />
19<center><div id="wuhan_weather">數據區域</div></center>
20<hr />
21<div id=stext>代碼區</div>
22
23<script language="javascript">
24
25 var xmlhttp ;
26 function getweather()
27 {
28 window.status = '';
29 document.all("load").style.display='';
30 xmlhttp = new activexobject("msxml2.xmlhttp");
31 xmlhttp.onreadystatechange = getready;
32 xmlhttp.open("get",document.getelementbyid('wurl').value,true);
33 xmlhttp.send(null);
34}
35function getready()
36{
37 window.status += xmlhttp.readystate+' ';
38 if(xmlhttp.readystate == 4)
39 {
40 document.all("load").style.display='none';
41 if(xmlhttp.status == 200)
42 {
43 var xmlreturn = xmlhttp.responsetext;
44
45 document.all("wuhan_weather").innerhtml=xmlreturn;
46 document.all("stext").innertext=xmlreturn;
47
48
49 var newtext = xmlreturn.replace(//n+/g,' ');
50 //document.all("stext").innertext=newtext;
51 var re = /<table .+?table>/ig;
52 var citytext = newtext.match(re);
53 document.all("city").innerhtml=citytext[2];
54
55 }
56 else
57 {
58 document.all("wuhan_weather").innerhtml="<b>出現錯誤:</b><br />"+new date()+"<br />"+xmlhttp.statustext+"<br />"+xmlhttp.status;
59 document.all("stext").innerhtml="代碼區";
60 document.all("city").innerhtml="片斷";
61
62 }
63 xmlhttp = null;
64 }
65
66}
67
68</script>
69</body>
70</html>
71
新聞熱點
疑難解答
圖片精選