在没有使用Ajax之前,总觉得Ajax很神秘,局部刷新、与服务器通信等,知道学习了Ajax之后,了解了Ajax语法之后,知道了其语法相当精简,扼要。下面就来说一说Ajax的精妙
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
XMLHttpRequest是Ajax的基础
现在大部分浏览器均支持XMLHttpRequest对象(部分IE5 、IE6使用ActiveXObject)
XMLHttpRequest用于在后台与服务器的数据交换,在不重新加载整个网页的情况下,对网页的部分内容进行加载
在调用Ajax时,需要先创建XMLHttpRequest对象
variable = new XMLHttpRequest();
而在老版本的IE中使用该Acticex对象
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");
}
向服务器发送请求
如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
方法 | 描述 |
---|---|
open(method,url,async) | 规定请求的类型、URL 以及是否异步处理请求。
|
send(string) | 将请求发送到服务器。
|
GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
- 无法使用缓存文件(更新服务器上的文件或数据库)
- 向服务器发送大量数据(POST 没有数据量限制)
- 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
常用的情况是:
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 发生变化。
|
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(),具体参考例子:
<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>
来源:oschina
链接:https://my.oschina.net/u/101114/blog/661083