1.概念:
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。
2.使用原生ajax请求过程:
过程详解:
2.1构造一个button按钮,并且使用document.getElementByID()方法寻找元素,并且使用使用addEventListener给元素绑定点击事件。
2.2点击绑定的函数内容
2..2.1创建XMLHttpRequest对象
2.2.2使用对象中的open方法,定义(请求方式,ulr/file,是否同意异步)
2.2.3这时在后面打印readystate状态码,这时已经是1了,也就是与服务器建立连接
2.2.4请求方法有两种onload,onreadyStateChange
2.2.5在请求方法里写入需要得到的响应内容比如responseText
2.2.6最后什么都配置了就向服务器发送请求
代码详解
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>ajax1-请求纯文本</title>
</head>
<body>
<button type="button" name="button"id="button">请求纯文本</button>
<script type="text/javascript">
document.getElementById("button").addEventListener("click",loadText);
function loadText() {
//console.log("hello world");
var xhr=new XMLHttpRequest();
//使用open方法
xhr.open("GET","sample.txt",true);
//两种ajax方法请求onload/onreadystatechange
xhr.onload=function(){
console.log(this.responseText);
}
//请求方法2
xhr.onreadystatechange=function(){
console.log("readystate"+readystate);//打印状态码
console.log(this.responseText);
}
//发送请求
xhr.send();
}
</script>
</body>
</html>