曾用jquery的集成ajax,现在来学学JavaScript原生的ajax。。。
下面是一个ajax请求服务端一个xml内容的简单实验。。。(来源于JavaScript程序设计)
步骤一:在服务器上,新建一个xml,命名为simpleAjax.xml,输入该文件中的内容是:This is the content of the simpleAjax.xml from server!
步骤二:在服务器上,新建一个html,命名为simpleAjax.html,与刚才建的simpleAjax.xml放在同一个目录下。
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>
- simpleAjax
- </title>
- <script type="text/javascript">
- var xmlHttpRequest; //XMLHttpRequest对象名
- function sendRequest() { //发送http请求
- getXMLHttpRequest(); //获得一个XMLHttpRequest对象到xmlHttpRequest
- xmlHttpRequest.onreadystatechange = stateChange; //http状态变化时执行的操作
- xmlHttpRequest.open("GET","simpleAjax.xml"); //连接
- xmlHttpRequest.send(null); //向服务器发送请求(这里内容为空)
- }
- function getXMLHttpRequest() {
- if(window.ActiveXObject) { //IE类
- xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
- }
- else if(window.XMLHttpRequest) { //Chrome类
- xmlHttpRequest = new XMLHttpRequest();
- }
- }
- function stateChange() {
- if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { //请求已完成且状态OK
- alert(xmlHttpRequest.responseText); //作出的反应
- }
- }
- </script>
- </head>
- <body>
- <form action="#">
- <input type="button" value="Send Asynchronous Request" onclick="sendRequest();" />
- </form>
- </body>
- </html>
步骤三:浏览器访问。
Chrome的结果:
IE的结果:
小结:获取XMLHttpRequest对象 ——>> 设置状态改变的动作 ——>> 连接 ——>> 发送请求。