AJAX是什么html
AJAX 全称为 Asynchronous JavaScript And XML,是一种从网页访问 Web 服务器的技术AJAX 的做用有从 web 服务器请求数据以及显示或使用数据。web
AJAX实例服务器
能够用一个本地文件来演示一下,咱们将本身写的一个txt文件的路径做为url的值,以下。异步
<!DOCTYPE html>async <html>ide <body>函数
<div id="demo">this <h1>XMLHttpRequest 对象</h1>url <button type="button" οnclick="loadDoc()">点击此处打开文件</button>3d </div>
<script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "1.txt", true); xhttp.send(); } </script>
</body> </html> |
<div> 用于显示来自服务器的信息。
<button> 被点击时就会调用函数。
下图1为结果,图2为点击按钮后的结果。
图1
图2
AJAX请求
XMLHttpRequest 对象用于同服务器交换数据,也就是向服务器发送请求,也就是上面实例化中的xhttp.open()。括号中的主要参数以下‘
method 请求的类型:
GET 仍是 POST
url, 服务器(文件)位置
async true(异步)或 false(同步),不填默认为异步
AJAX响应
发服务器发送请求成功事后,服务器会有相应的响应,要从下面一些相应的属性来理解。
Onreadystatechange定义了当 readyState 属性发生改变时所调用的函数。
readyState保存了 XMLHttpRequest 的状态,不一样的状态由数字表示
0: 请求未初始化
1: 服务器链接已创建
2: 请求已接收
3: 正在处理请求
4: 请求已完成且响应已就绪
Status存有 XMLHttpRequest 对象的状态。好比404就是页面丢失(Page not found),200就是完成(Ok)。
当 readyState 为 4,status 为 200 时,响应就绪。
END