Ajax异步请求的五个步骤及实战案例

前言

AJAX(Asynchronous JavaScript and XML):是指一种创建交互式网页应用的网页开发技术,通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这就意味着可以在不重新加载整个网页的情况下,对网页的局部进行更新。

1.建立xmlHttpRequest异步对象

const xhr=new XMLHttpRequest();

2.创建HTTP请求(设置请求方法和URL)

//get方式
xhr.open('GET',URL);
 
//post方式发送数据,需要设置请求头
xhr.open('POST',URL);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

除了method和URL两个必选参数外还有三个可选参数:flag,name,password

flag:参数值为布尔类型,用于指定是否用异步方式。true表异步,false表同步,默认为true。

name:

3.发送数据

//get不需要传递参数
xhr.send(null);
 
//post必须有参数
xhr.send('a=100&b=200&c=300');

4.设置回调函数

xhr.onreadystatechange = callback;

5.在回调函数中对不同的响应状态进行处理

function callback() {
 //判断响应状态码
 if(xhr.readyState===4){
 // 判断交互是否成功
 if(xhr.status>=200&&xhr.status<300){
 // console.log(xhr.status);//状态码
 // console.log(xhr.statusText);//状态字符串
 // console.log(xhr.getAllResponseHeaders());//所有响应头
 // console.log(xhr.response);//响应体
 
 // 获取服务器响应的数据
 result.innerHTML=xhr.response;
 }else{
 
 }
 }
}

ajax中的readyState属性

  • 0:未初始化。尚未调用 open()方法。
  • 1:启动。已经调用 open()方法,但尚未调用 send()方法。
  • 2:发送。已经调用 send()方法,但尚未接收到响应。
  • 3:接收。已经接收到部分响应数据。
  • 4:完成。已经接收到全部响应数据,而且已经可以在客户端使用了。

只有在XMLHttpRequest对象完成了以上5个步骤之后,才可以获取从服务器端返回的数据。

ajax中的状态码(200-300则表示响应成功)

  • 400:请求参数错误
  • 401:无权限访问
  • 404:访问的资源不存在

案例实现

案例:获取天气信息

格式要求:使用HTML创建一个输入框,一个按钮,在输入框中输入文字后点击按钮,即可在下面打印未来15天的天气

输出要求:每个天气要求:城市名,温度,天气,风向,风力

API网站:(https://www.apishop.net/#/)

APIKEY:***************

使用 $.get( ) 获取:

var text = $('#text')
var btn = $('#button')
var div = $('#div1')
btn.click(function(){
 var city = text.val()
 var url = "https://api.apishop.net/common/weather/get15DaysWeatherByArea?apiKey=******="+ city

 $.get(url, function(response){
 console.log(response)
 var list = response.result.dayList;
 console.log(list)
 for(var i = 0; i < list.length; i++){
 div.append("<ul>")
 div.append("<li>" + list[i].area + "</li>")
 div.append("<li>" + list[i].day_air_temperature + "</li>")
 div.append("<li>" + list[i].day_weather + "</li>")
 div.append("<li>" + list[i].day_wind_direction + "</li>")
 div.append("<li>" + list[i].day_wind_power + "</li>")
 div.append("</ul>")
 }

 }, "JSON")
})

使用 $.post( ) 获取:

var text = $('#text')
var btn = $('#button')
var div = $('#div1')
btn.click(function(){
 var url = "https://api.apishop.net/common/weather/get15DaysWeatherByArea?apiKey=******&area="

 $.post(url,{
 // 传入必须的参数
 area:text.val()
 }, function(response){
 console.log(response)
 var list = response.result.dayList;
 console.log(list)
 for(var i = 0; i < list.length; i++){
 div.append("<ul>")
 div.append("<li>" + list[i].area + "</li>")
 div.append("<li>" + list[i].day_air_temperature + "</li>")
 div.append("<li>" + list[i].day_weather + "</li>")
 div.append("<li>" + list[i].day_wind_direction + "</li>")
 div.append("<li>" + list[i].day_wind_power + "</li>")
 div.append("</ul>")
 }

 }, "JSON")
 })

结果截图:

总结

作者:随便944原文地址:https://blog.csdn.net/qq_62380657/article/details/124597221

%s 个评论

要回复文章请先登录注册