Ajax学习体验之一

在没有使用Ajax以前,总以为Ajax很神秘,局部刷新、与服务器通讯等,知道学习了Ajax以后,了解了Ajax语法以后,知道了其语法至关精简,扼要。下面就来讲一说Ajax的精妙 javascript

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。 html

XMLHttpRequest是Ajax的基础 java

如今大部分浏览器均支持XMLHttpRequest对象(部分IE5 、IE6使用ActiveXObject) ajax

XMLHttpRequest用于在后台与服务器的数据交换,在不从新加载整个网页的状况下,对网页的部份内容进行加载 数据库


在调用Ajax时,须要先建立XMLHttpRequest对象 浏览器

    variable = new XMLHttpRequest(); 缓存

而在老版本的IE中使用该Acticex对象 服务器

    variable = new ActiveXobject(“Microsoft.XMLHTTP”); dom


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");
  }

向服务器发送请求

如需将请求发送到服务器,咱们使用 XMLHttpRequest 对象的 open() 和 send() 方法: 异步

xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
方法 描述
open(method,url,async)

规定请求的类型、URL 以及是否异步处理请求。

  • method:请求的类型;GET 或 POST
  • url:文件在服务器上的位置
  • async:true(异步)或 false(同步)
send(string)

将请求发送到服务器。

  • string:仅用于 POST 请求

GET 仍是 POST?

与 POST 相比,GET 更简单也更快,而且在大部分状况下都能用。

然而,在如下状况中,请使用 POST 请求:

  • 没法使用缓存文件(更新服务器上的文件或数据库)
  • 向服务器发送大量数据(POST 没有数据量限制)
  • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
具体参见:http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_send.asp


经常使用的状况是:

xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
上面的例子,可能会读取到缓存结果,为了不这种状况,能够向URL中添加一个惟一的ID

xmlhttp.open("GET","demo_get.asp?t=" +Math.random(),true);
xmlhttp.send();

onreadystatechange 事件

当请求被发送到服务器时,咱们须要执行一些基于响应的任务。

每当 readyState 改变时,就会触发 onreadystatechange 事件。

readyState 属性存有 XMLHttpRequest 的状态信息。

下面是 XMLHttpRequest 对象的三个重要的属性:

属性 描述
onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState

存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

  • 0: 请求未初始化
  • 1: 服务器链接已创建
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪
status

200: "OK"

404: 未找到页面

在 onreadystatechange 事件中,咱们规定当服务器响应已作好被处理的准备时所执行的任务。

当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

函数回调 callback(),具体参考例子:

<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>
相关文章
相关标签/搜索