Ajax运行原理
Ajax相当于浏览器发送请求与接受响应的代理人,以实现不影响用户浏览页面的情况下,局部更新页面数据,从而提高用户体验
实现步骤
- 创建Ajax对象
new XMLHttpRequest()
- 告诉Ajax请求地址以及请求方式
open
- 发送请求
send
方法 - 获取服务器端给予客户端的响应数据 onload 获取响应数据
responseText
查看答案
1 2 3 4 5 6 7 8 9 10
| var xhr = new XMLHttpRequest()
xhr.open('get', 'http://localhost:3000/first')
xhr.send()
xhr.onload = function(){ console.log(xhr.responseText); }
|
响应的数据格式
- json对象作为响应数据的格式,请求返回的数据为json字符串
- 将json字符串转化为json对象
查看答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var xhr = new XMLHttpRequest()
xhr.open('get', 'http://localhost:3000/responseData')
xhr.send()
xhr.onload = function(){
let respnseText = JSON.parse(xhr.responseText) console.log(respnseText); console.log(typeof respnseText);
let str = `<h2>${respnseText.name}</h2>` document.body.innerHTML = str }
|
请求参数传递
- get请求
xx.open('get',url)
查看答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| let username =document.querySelector('#username') let email =document.querySelector('#email') let submit =document.querySelector('#submit')
submit.onclick = function(){ let emaildata = email.value let usernamedata = username.value let str = `username=${usernamedata}&email=${emaildata}` console.log(str); let xhr = new XMLHttpRequest() xhr.open('get',`http://localhost:3000/get?${str}`) xhr.send() xhr.onload = function(){ console.log(xhr.responseText); } }
|
post请求方式
- xhr.set