AJAX:异步的JS和XML(Asynchronous JavaScript And XML)
在不重新加载页面的情况下,AJAX通过加载后台数据,显示在页面中
1.AJAX XHR
创建XMLHttpRequest对象
语法:
variable=new XMLHttpRequest();
XMLHttpRequest 用于在后台与服务器交换数据。
向服务器发送请求:使用XHR的open()和send()方法
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
1无法使用缓存文件(更新服务器上的文件或数据库)
2向服务器发送大量数据(POST 没有数据量限制)
3发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
GET:从指定的资源请求数据
POST:向指定的资源提交要处理的数据
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mydiv").innerHTML = xmlhttp.responseText;
}
else {
alert("there was a problem with the request");
}
}
xmlhttp.open("GET", "HtmlPage2.html?t="+Math.random(), true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button"onclick="loadXMLDoc()">请求数据</button>
<div id="mydiv"></div>
</body>
</html>
2.服务器响应
如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性
3.onreadystatechange事件
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。