JavaScript: js XMLHttpRequest发送Ajax请求
1. 什么XMLHttpRequest
XMLHttpRequest(简称 xhr)是浏览器提供的 Javascript 对象,通过它,可以请求服务器上的数据资源。之前所学的 jQuery 中的 Ajax 函数,就是基于 xhr 对象封装出来的。
2. 使用xhr发起GET请求
步骤:
- 创建 xhr 对象
- 调用 xhr.open() 函数
- 调用 xhr.send() 函数
- 监听 xhr.onreadystatechange 事件
例子:
// 1. 创建 XHR 对象 var xhr = new XMLHttpRequest() // 2. 调用 open 函数,指定 请求方式 与 URL地址 xhr.open('GET', 'http://www.domain.com/') // 3. 调用 send 函数,发起 Ajax 请求 xhr.send() // 4. 监听 onreadystatechange 事件 xhr.onreadystatechange = function() { // 4.1 监听 xhr 对象的请求状态 readyState ;与服务器响应的状态 status if (xhr.readyState === 4 && xhr.status === 200) { // 4.2 打印服务器响应回来的数据 console.log(xhr.responseText) } }
了解xhr对象的readyState属性
XMLHttpRequest 对象的 readyState 属性,用来表示当前 Ajax 请求所处的状态。每个 Ajax 请求必然处于以下状态中的一个:
值 | 状态 | 描述 |
0 | UNSENT | XMLHttpRequest 对象已被创建,但尚未调用 open方法。 |
1 | OPENED | open() 方法已经被调用。 |
2 | HEADERS_RECEIVED | send() 方法已经被调用,响应头也已经被接收。 |
3 | LOADING | 数据接收中,此时 response 属性中已经包含部分数据。 |
4 | DONE | Ajax 请求完成,这意味着数据传输已经彻底完成或失败。 |
使用xhr发起带参数的GET请求
使用 xhr 对象发起带参数的 GET 请求时,只需在调用 xhr.open 期间,为 URL 地址指定参数即可:
// ...省略 xhr.open('GET', 'http://www.domain.com/') // ...省略
这种在 URL 地址后面拼接的参数,叫做查询字符串。
3. 使用xhr发起POST请求
步骤:
- 创建 xhr 对象
- 调用 xhr.open() 函数
- 设置 Content-Type 属性(固定写法)
- 调用 xhr.send() 函数,同时指定要发送的数据
- 监听 xhr.onreadystatechange 事件
例子:
// 1. 创建 xhr 对象 var xhr = new XMLHttpRequest() // 2. 调用 open() xhr.open('POST', 'http://www.domain.com/') // 3. 设置 Content-Type 属性(固定写法) xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') // 4. 调用 send(),同时将数据以查询字符串的形式,提交给服务器 xhr.send('bookname=水浒传&author=施耐庵&publisher=天津图书出版社') // 5. 监听 onreadystatechange 事件 xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) } }