1. 传统表单提交与AJAX比较
1.1 Form表单
<form action="/form.html" method="post">
<input type="text" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" />
</form>
- 它支持持GET和POST类型
- 提交数据后页面会刷新,用户体验差
1.2 AJAX
- 概念
AJAX = Asynchronous JavaScript and XML (异步的JavaScript 和 XML) - 使用内置的
XMLHttpRequest
和fetch
对象,实现和服务器的交互 - 交互数据时不需要刷新数据,用户体验好
1.2.1 XMLHttpRequest
GET 请求
- 创建对象
- 配置参数
- 绑定事件
- 发送请求
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function(){
}
xhr.send()
方法1
let url = 'http://xxx.xxx.com/api/blog/list'
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status < 300