耐人寻味

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
We now have enough information to bring together the complete lifecycle of loading a document, as illustrated in listing 2.11. We instantiate the XMLHttp-Request object, tell it to load a document, and then monitor that load process asynchronously using callback handlers. In the simple example, we define a DOM node called console, to which we can output status information, in order to get a written record of the download process.

sample 2.11:
 1<html>
 2<head>
 3<script type='text/javascript'>
 4var req=null;
 5var console=null;
 6var READY_STATE_UNINITIALIZED=0;
 7var READY_STATE_LOADING=1;
 8var READY_STATE_LOADED=2;
 9var READY_STATE_INTERACTIVE=3;
10var READY_STATE_COMPLETE=4;
11function sendRequest(url,params,HttpMethod){
12if (!HttpMethod){
13HttpMethod="GET";
14}

15req=initXMLHTTPRequest();
16if (req){
17req.onreadystatechange=onReadyState;
18req.open(HttpMethod,url,true);
19req.setRequestHeader
20("Content-Type""application/x-www-form-urlencoded");
21req.send(params);
22}

23}

24function initXMLHTTPRequest(){
25var xRequest=null;
26if (window.XMLHttpRequest){
27xRequest=new XMLHttpRequest();
28}
 else if (window.ActiveXObject){
29xRequest=new ActiveXObject
30("Microsoft.XMLHTTP");
31}

32return xRequest;
33}

34function onReadyState(){
35var ready=req.readyState;
36var data=null;
37if (ready==READY_STATE_COMPLETE){
38data=req.responseText;
39}
else{
40data="loading["+ready+"]";
41}

42toConsole(data);
43}

44function toConsole(data){
45if (console!=null){
46var newline=document.createElement("div");
47console.appendChild(newline);
48var txt=document.createTextNode(data);
49newline.appendChild(txt);
50}

51}

52window.onload=function(){
53console=document.getElementById('console');
54sendRequest("data.txt");
55}

56
</script>
57</head>
58<body>
59<div id='console'></div>
60</body>
61</html>
posted on 2006-06-07 19:46  martinfly  阅读(158)  评论(0编辑  收藏  举报