Web_JavaScript_AJAX_AJAX基础知识;

本文深入介绍了AJAX技术,包括其工作原理、与服务器交互的方法、处理服务器响应的方式以及多个实用的AJAX应用实例,帮助读者掌握异步JavaScript和XML的核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AJAX 教程 2014-12-24 15:16
引言:AJAX_ Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。AJAX 不是新的编程语言,而是一种使用现有标准的新方法。AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。


一、AJAX 简介
前言:AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
1、什么是 AJAX ?
AJAX = 异步 JavaScript 和 XML。AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页页面。有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。


2、Google Suggest
在 2005 年,Google 通过其 Google Suggest 使 AJAX 变得流行起来。Google Suggest 使用 AJAX 创造出动态性极强的 web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。




二、AJAX 实例
<html>
<head>
<script type="text/javascript">
function loadXMLDoc() {
            var xmlhttp;
            if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "/ajax/demo_get.asp", true);
            xmlhttp.send();
        }
</script>
</head>
<body>
<div id="myDiv">
<h3>Let AJAX change this text</h3>
</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>


<AJAX XHR>
三、AJAX - 创建 XMLHttpRequest 对象
前言:XMLHttpRequest 是 AJAX 的基础。
1、XMLHttpRequest 对象
所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。
XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。


2、创建 XMLHttpRequest 对象
说明:所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。
语法:variable = new XMLHttpRequest();
[IE5、IE6使用 ActiveX 对象:variable = new ActiveXObject("Microsoft.XMLHTTP");]
兼容:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}




四、AJAX - 向服务器发送请求
前言:XMLHttpRequest 对象用于和服务器交换数据。
open(method,url,async):规定请求的类型、URL 以及是否异步处理请求;method:请求的类型;GET 或 POST。url:文件在服务器上的位置。async:true(异步)或 false(同步)。
send(string):将请求发送到服务器。string:仅用于 POST 请求
1、向服务器发送请求
// 如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法
xmlhttp.open("GET","test.txt",true);
xmlhttp.send();


2、GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
(1)、无法使用缓存文件(更新服务器上的文件或数据库);
(2)、向服务器发送大量数据(POST 没有数据量限制);
(3)、发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠;


3、GET 请求
->html页面
<html>
<head>
    <script type="text/javascript">
        function loadXMLDoc() {
            var xmlhttp;
            if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "/ajax/demo_get.asp", true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <h2>AJAX</h2>
    <button type="button" onclick="loadXMLDoc()">请求数据</button>
    <div id="myDiv"></div>
</body>
</html>
注意:如果您希望通过 GET 方法发送信息,请向 URL 添加信息:xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);


4、POST 请求
setRequestHeader(header,value):向请求添加 HTTP 头。header: 规定头的名称;value: 规定头的值;
//如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
->html页面
<script type="text/javascript">
function loadXMLDoc() {
    // 创建
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 监听
    xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
    }
    // 请求
    xmlhttp.open("POST", "/ajax/demo_post2.asp", true);
    // 头部
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // 发送
    xmlhttp.send("fname=Bill&lname=Gates");
}
</script>


5、url - 服务器上的文件
open() 方法的 url 参数是服务器上文件的地址:该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)。


6、异步 - True 或 False?
AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true;对于 web 开发人员来说,发送异步请求是一个巨大的进步。很多在服务器执行的任务都相当费时。AJAX 出现之前,这可能会引起应用程序挂起或停止。
通过 AJAX,JavaScript 无需等待服务器的响应,而是:在等待服务器响应时执行其他脚本;当响应就绪后对响应进行处理;


7、Async = true
//当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();


8、Async = false
如需使用 async=false,请将 open() 方法中的第三个参数改为 false;
我们不推荐使用 async=false,但是对于一些小型的请求,也是可以的。请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。
注释:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可;




五、AJAX - 服务器响应
说明:如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
responseText,获得字符串形式的响应数据。
responseXML, 获得 XML 形式的响应数据。
1、responseText 属性
如果来自服务器的响应并非 XML,请使用 responseText 属性。
responseText 属性返回字符串形式的响应,因此您可以这样使用:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;


2、responseXML 属性
如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性:
//请求 books.xml 文件,并解析响应:
->books.xml
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>
->html页面
<script type="text/javascript">
function loadXMLDoc() {
    var xmlhttp;
    var txt, x, i;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   xmlDoc = xmlhttp.responseXML;
   txt = "";
   x = xmlDoc.getElementsByTagName("title");
   for (i = 0; i < x.length; i++) {
txt = txt + x[i].childNodes[0].nodeValue + "<br />";
   }
   document.getElementById("myDiv").innerHTML = txt;
}
    }
    xmlhttp.open("GET", "/example/xmle/books.xml", true);
    xmlhttp.send();
}
</script>




六、AJAX - onreadystatechange 事件
1、onreadystatechange 事件
背景:当请求被发送到服务器时,我们需要执行一些基于响应的任务。每当 readyState 改变时,就会触发 onreadystatechange 事件。readyState 属性存有 XMLHttpRequest 的状态信息。
XHR对象三大属性:
(1)、onreadystatechange
存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
(2)、readyState
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。0: 请求未初始化;1: 服务器连接已建立;2: 请求已接收;3: 请求处理中;4: 请求已完成,且响应已就绪;
(3)、status
200: "OK"; 404: 未找到页面;
切记:在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
// 当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
注释:onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。


2、使用 Callback 函数
callback 函数是一种以参数形式传递给另一个函数的函数。如果您的网站上存在多个 AJAX 任务,那么您应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。
// 该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同)
<html>
<head>
    <script type="text/javascript">
        var xmlhttp;
        function loadXMLDoc(url, cfunc) {
            if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = cfunc;
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
        function myFunction() {
            loadXMLDoc("/ajax/test1.txt", function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            });
        }
    </script>
</head>
<body>
    <div id="myDiv">
        <h2>Let AJAX change this text</h2>
    </div>
    <button type="button" onclick="myFunction()">通过 AJAX 改变内容</button>
</body>
</html>




七、AJAX ASP/PHP 请求实例
引言:AJAX 用于创造动态性更强的应用程序。
实例:匹配
->html页面
<html>
<head>
    <script type="text/javascript">
        function showHint(str) {
            var xmlhttp;
            if (str.length == 0) {
                document.getElementById("txtHint").innerHTML = "";
                return;
            }
            if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "/ajax/gethint.asp?q=" + str, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <h3>键入字母(A - Z):</h3>
    <form action="">
        姓氏:
        <input type="text" id="txt1" onkeyup="showHint(this.value)" />
    </form>
    <p>建议:<span id="txtHint"></span>
    </p>
</body>
</html>
->gethint.php_AJAX 服务器页面 (PHP)
<?php
//1/名字数组:用名字来填充数组;
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";


//获得来自 URL 的 q 参数
$q=$_GET["q"];


//2/比较:如果 q 大于 0,则查找数组中的所有提示;
if (strlen($q) > 0)
 {
 $hint="";
 for($i=0; $i<count($a); $i++)
   {
   if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
     {
     if ($hint=="")
{
$hint=$a[$i];
}
     else
{
$hint=$hint." , ".$a[$i];
}
     }
   }
 }


//3/响应:如果未找到提示,则把输出设置为 "no suggestion";
// 否则设置为正确的值
if ($hint == "")
 {
 $response="no suggestion";
 }
else
 {
 $response=$hint;
 }


//输出响应
echo $response;
?>


八、AJAX 数据库实例
前言:AJAX 可用来与数据库进行动态通信。
功能:网页如何通过 AJAX 从数据库读取信息
->html页面
<html>
<head>
    <script type="text/javascript">
        function showCustomer(str) {
            var xmlhttp;
            if (str == "") {
                document.getElementById("txtHint").innerHTML = "";
                return;
            }
            if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "/ajax/getcustomer.php?q=" + str, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <form action="" style="margin-top:15px;">
        <label>客户:
            <select name="customers" onchange="showCustomer(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;">
                <option value="APPLE">Apple Computer, Inc.</option>
                <option value="BAIDU ">BAIDU, Inc</option>
                <option value="Canon">Canon USA, Inc.</option>
                <option value="Google">Google, Inc.</option>
                <option value="Nokia">Nokia Corporation</option>
                <option value="SONY">Sony Corporation of America</option>
            </select>
        </label>
    </form>
    <br />
    <div id="txtHint">客户信息</div>
</body>
</html>
->selectuser.js(代替头部脚本)
// xhr对象
var xmlHttp;
// showUser函数
function showUser(str)

// 获取xhr对象
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}


// ajax请求
var url="getuser.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
// stateChanged监听函数
function stateChanged() 

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

document.getElementById("txtHint").innerHTML=xmlHttp.responseText 

}
// 创建xhr对象
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
 {
 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 }
catch (e)
 {
 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
}
return xmlHttp;
}
->getuser.php
<?php
// 获取q请求参数
$q=$_GET["q"];

// 链接对象
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// 选数据库
mysql_select_db("ajax_demo", $con);

// 查询数据
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);


// 响应请求
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";


// 关闭连接
mysql_close($con);
?>




九、AJAX XML 实例
引言:AJAX 可用来与 XML 文件进行交互式通信。
功能:网页如何使用 AJAX 来读取来自 XML 文件的信息
->cd_catalog.xml
<CATALOG>
<CD>
<TITLE>主题</TITLE>
<ARTIST>作家</ARTIST>
<COUNTRY>国家</COUNTRY>
<COMPANY>公司</COMPANY>
<PRICE>价格</PRICE>
<YEAR>年份</YEAR>
</CD>
</CATALOG>
->html页面
<html>
<head>
    <script type="text/javascript">
        function loadXMLDoc(url) {
            var xmlhttp;
            var txt, x, xx, i;
            if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    txt = "<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
                    x = xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
                    for (i = 0; i < x.length; i++) {
                        txt = txt + "<tr>";
                        xx = x[i].getElementsByTagName("TITLE"); {
                            try {
                                txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
                            } catch (er) {
                                txt = txt + "<td> </td>";
                            }
                        }
                        xx = x[i].getElementsByTagName("ARTIST"); {
                            try {
                                txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
                            } catch (er) {
                                txt = txt + "<td> </td>";
                            }
                        }
                        txt = txt + "</tr>";
                    }
                    txt = txt + "</table>";
                    document.getElementById('txtCDInfo').innerHTML = txt;
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <div id="txtCDInfo">
        <button onclick="loadXMLDoc('/example/xmle/cd_catalog.xml')">获得 CD 信息</button>
    </div>
</body>
</html>




十、AJAX 实例
1、加载文本文件进入HTML元素
<html>
<head>
    <script type="text/javascript">
        var xmlhttp;
/// 加载数据函数
        function loadXMLDoc(url) {
   // 创建xhr对象
            xmlhttp = null;
            if (window.XMLHttpRequest) { // code for Firefox, Opera, IE7, etc.
                xmlhttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xmlhttp != null) {
                // 准备状态监听
xmlhttp.onreadystatechange = state_Change;
                // 打开请求
xmlhttp.open("GET", url, true);
// 发送请求
                xmlhttp.send(null);
            } else {
                alert("Your browser does not support XMLHTTP.");
            }
        }
/// 准备状态处理函数
        function state_Change() {
            if (xmlhttp.readyState == 4) { // 4 = "loaded"
                if (xmlhttp.status == 200) { // 200 = "OK"
                    document.getElementById('T1').innerHTML = xmlhttp.responseText;
                } else {
                    alert("Problem retrieving data:" + xmlhttp.statusText);
                }
            }
        }
    </script>
</head>
<body onload="loadXMLDoc('/example/ajax/test_xmlhttp.txt')">
    <div id="T1" style="border:1px solid black;height:60;width:500;padding:5"></div>
    <br />
    <button onclick="loadXMLDoc('/example/ajax/test_xmlhttp2.txt')">Click</button>
</body>
</html>


2、加载XML文件
->note.xml(提醒)
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
->html page
<html>
<head>
    <script type="text/javascript">
        var xmlhttp;
/// 加载数据函数
        function loadXMLDoc(url) {
            xmlhttp = null;
            if (window.XMLHttpRequest) { // code for IE7, Firefox, Opera, etc.
                xmlhttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xmlhttp != null) {
                xmlhttp.onreadystatechange = state_Change;
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
            } else {
                alert("Your browser does not support XMLHTTP.");
            }
        }
        function state_Change() {
            if (xmlhttp.readyState == 4) { // 4 = "loaded"
                if (xmlhttp.status == 200) { // 200 = "OK"
                    document.getElementById('A1').innerHTML = xmlhttp.status;
                    document.getElementById('A2').innerHTML = xmlhttp.statusText;
                    document.getElementById('A3').innerHTML = xmlhttp.responseText;
                } else {
                    alert("Problem retrieving XML data:" + xmlhttp.statusText);
                }
            }
        }
    </script>
</head>
<body>
    <h2>Using the HttpRequest Object</h2>
    <p><b>Status:</b>
        <span id="A1"></span>
    </p>
    <p><b>Status text:</b>
        <span id="A2"></span>
    </p>
    <p><b>Response:</b>
        <br /><span id="A3"></span>
    </p>
    <button onclick="loadXMLDoc('/example/xmle/note.xml')">Get XML</button>
</body>
</html>


3、简单Head请求
<html>
<head>
    <script type="text/javascript">
        var xmlhttp;
        function loadXMLDoc(url) {
            xmlhttp = null;
            if (window.XMLHttpRequest) { // code for Firefox, Mozilla, IE7, etc.
                xmlhttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xmlhttp != null) {
                xmlhttp.onreadystatechange = state_Change;
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
            } else {
                alert("Your browser does not support XMLHTTP.");
            }
        }
        function state_Change() {
            if (xmlhttp.readyState == 4) { // 4 = "loaded"
                if (xmlhttp.status == 200) { // 200 = "OK"
                    document.getElementById('p1').innerHTML = xmlhttp.getAllResponseHeaders();
                } else {
                    alert("Problem retrieving data:" + xmlhttp.statusText);
                }
            }
        }
    </script>
</head>
<body>
    <p id="p1">paragraph</p>
    <button onclick="loadXMLDoc('/example/ajax/test_xmlhttp.txt')">Get Headers</button>
</body>
</html>


4、复杂Head请求
<html>
<head>
    <script type="text/javascript">
        var xmlhttp;
        function loadXMLDoc(url) {
            xmlhttp = null;
            if (window.XMLHttpRequest) { // all modern browsers
                xmlhttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // for IE5, IE6
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xmlhttp != null) {
                xmlhttp.onreadystatechange = state_Change;
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
            } else {
                alert("Your browser does not support XMLHTTP.");
            }
        }
        function state_Change() {
            if (xmlhttp.readyState == 4) { // 4 = "loaded"
                if (xmlhttp.status == 200) { // 200 = "OK"
                    document.getElementById('p1').innerHTML = "This file was last modified on: " + xmlhttp.getResponseHeader('Last-Modified');
                } else {
                    alert("Problem retrieving data:" + xmlhttp.statusText);
                }
            }
        }
    </script>
</head>
<body>
    <p id="p1">paragraph</p>
    <button onclick="loadXMLDoc('/example/ajax/test_xmlhttp.txt')">Get "Last-Modified"</button>
</body>
</html>


5、把 XML 文件显示为 HTML 表格
->xml
<CATALOG>
    <CD>
        <TITLE>主题</TITLE>
        <ARTIST>作者</ARTIST>
        <COUNTRY>国家</COUNTRY>
        <COMPANY>公司</COMPANY>
        <PRICE>价钱</PRICE>
        <YEAR>年份</YEAR>
    </CD>
</CATALOG>
->html
<html>
<head>
    <script type="text/javascript">
        var xmlhttp;
        function loadXMLDoc(url) {
            xmlhttp = null;
            if (window.XMLHttpRequest) { // code for IE7, Firefox, Mozilla, etc.
                xmlhttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // code for IE5, IE6
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xmlhttp != null) {
                xmlhttp.onreadystatechange = onResponse;
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
            } else {
                alert("Your browser does not support XMLHTTP.");
            }
        }
        function onResponse() {
            if (xmlhttp.readyState != 4) return;
            if (xmlhttp.status != 200) {
                alert("Problem retrieving XML data");
                return;
            }
            txt = "<table border='1'>";
            x = xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
            for (i = 0; i < x.length; i++) {
                txt = txt + "<tr>";
                xx = x[i].getElementsByTagName("TITLE"); {
                    try {
                        txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
                    } catch (er) {
                        txt = txt + "<td> </td>";
                    }
                }
                xx = x[i].getElementsByTagName("ARTIST"); {
                    try {
                        txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
                    } catch (er) {
                        txt = txt + "<td> </td>";
                    }
                }
                txt = txt + "</tr>";
            }
            txt = txt + "</table>";
            document.getElementById('copy').innerHTML = txt;
        }
    </script>
</head>
<body>
    <div id="copy">
        <button onclick="loadXMLDoc('/example/xmle/cd_catalog.xml')">Get CD info</button>
    </div>
</body>
</html>


6、输入智能提示
功能:当用户键入文本时,通过使用 XML HTTP 与服务器进行在线通信;
->html
<html>
<head>
    <script type="text/javascript">
        var xmlHttp = null;
        function showHint(str) {
            if (str.length == 0) {
                document.getElementById("txtHint").innerHTML = "";
                return;
            }
            try { // Firefox, Opera 8.0+, Safari, IE7
                xmlHttp = new XMLHttpRequest();
            } catch (e) { // Old IE
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    alert("Your browser does not support XMLHTTP!");
                    return;
                }
            }
            var url = "/ajax/gethint.asp?q=" + str;
            url = url + "&sid=" + Math.random(); // 防止使用缓存;
            xmlHttp.open("GET", url, false);
            xmlHttp.send(null);
            document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
        }
    </script>
</head>
<body>
    <form>
        First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
    </form>
    <p>Suggestions: <span id="txtHint"></span>
    </p>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值