AJAX笔记原理篇

server/2025/2/5 5:31:26/

黑马程序员视频地址:

AJAX-Day03-01.XMLHttpRequest_基本使用https://www.bilibili.com/video/BV1MN411y7pw?vd_source=0a2d366696f87e241adc64419bf12cab&spm_id_from=333.788.videopod.episodes&p=33https://www.bilibili.com/video/BV1MN411y7pw?vd_source=0a2d366696f87e241adc64419bf12cab&spm_id_from=333.788.videopod.episodes&p=33

XMLHttpRequest

基本使用方法 

    //第一步:创建 XMLHttpRequest 对象const xhr = new XMLHttpRequest()//第二步:配置请求方法和请求 url 地址xhr.open("GET", "https://hmajax.itheima.net/api/province")//第三步:监听 loadend 事件,接收响应结果xhr.addEventListener("loadend", () => {//响应结果console.log(xhr.response)//得到的是字符串const object = JSON.parse(xhr.response) //字符串转对象console.log(object)})//第四步:发起请求xhr.send()

查询参数 

    //第二步:配置请求方法和请求 url 地址xhr.open("GET", "https://hmajax.itheima.net/api/area?pname=辽宁省&cname=大连市")

将  对象  快速转成  参数1=值1&参数2=值2...   的字符串格式

   //获取输入框的值const pname = document.querySelector(".province").valueconst cname = document.querySelector(".city").value//构建对象 (输入框数量多时,用serialiaze函数快速获取,得到的结果是对象,就可以直接使用)const valueObj = {pname,cname}//⭐️查询参数对象转成查询参数字符串const paramsObj = new URLSearchParams(valueObj)const queryString = paramsObj.toString()//创建XMR对象const xhr = new XMLHttpRequest()//配置参数xhr.open("GET", `https://hmajax.itheima.net/api/area?${queryString}`)//配置监听事件xhr.addEventListener("loadend", () => {console.log(xhr.response)})//发送请求xhr.send()

数据提交

    document.querySelector('.reg-btn').addEventListener('click', () => {//创建请求体实例对象const xhr = new XMLHttpRequest()//设置参数xhr.open("POST", "https://hmajax.itheima.net/api/register")//设置监听时间xhr.addEventListener("loadend", () => {console.log(xhr.response)})//⭐️设置请求头-告诉服务器数据类型xhr.setRequestHeader("Content-Type", "application/json")//准备提交的数据const userObj = {username: "admin123",password: "12345678"}const userStr = JSON.stringify(userObj)//设置请求体,发送请求xhr.send(userStr)})


Promise

基本使用方法

   //创建Promise对象const p = new Promise((resolve, reject) => {//执行异步任务-并传递结果//如果此处调用了resolve(),则接下来会让then()执行//如果此处调用了reject(),则接下来会让catch()执行})p.then(result => {//成功执行})p.catch(error => {//失败执行})

promise的三种状态


XHR与Promise联合使用

    const p = new Promise((resolve, reject) => {//创建XHR对象const xhr = new XMLHttpRequest()//设置参数xhr.open("GET", "https://hmajax.itheima.net/api/province123")//设置监听事件xhr.addEventListener("loadend", () => {//可以打印一下xhr对象看一下数据if(xhr.status >= 200 && xhr.status <= 300){//成功,调用resolve()让其自动调用then()resolve(JSON.parse(xhr.response))}else{//失败,调用reject()让其自动调用catch()reject(new Error(xhr.response))}})//发送请求体xhr.send()}).then(result => {//成功执行console.log(result)}).catch(error => {//失败执行,错误要用dir打印console.dir(error)})

dir打印结果 


封装简易版axios

简陋版(简单GET获取,不需要传参)

//封装函数function myAxios(object){return new Promise((resolve, reject) => {//创建XHR对象const xhr = new XMLHttpRequest()//设置属性xhr.open(object.method || "GET", object.url)//设置监听事件xhr.addEventListener("loadend", () => {if(xhr.status >= 200 && xhr.status < 300){//成功resolve(JSON.parse(xhr.response))}else{//失败reject(new Error(xhr.response))}})//发送请求体xhr.send()})}//调用myAxios({url: "https://hmajax.itheima.net/api/province"}).then(result => {console.log(result)}).catch(error => {console.log(error)})

完整版(GET/POST都可以用,可以携带参数)

//封装函数
function myAxios(object){return new Promise((resolve, reject) => {//创建XHR对象const xhr = new XMLHttpRequest()//设置属性if(obj.params){object.url += "?" + new URLSearchParams(object.params).toString()}xhr.open(object.method || "GET",  object.url)//设置监听事件xhr.addEventListener("loadend", () => {if(xhr.status >= 200 && xhr.status < 300){//成功resolve(JSON.parse(xhr.response))}else{//失败reject(new Error(xhr.response))}})//判断是否有data选项if(object.data){//设置请求头xhr.setRequestHeader("Content-Type", "application/json")const strdata = JSON.stringify(object.data)//发送请求体xhr.send(strdata)}else{//发送请求体xhr.send()}})}//调用(用户注册)
myAxios({url: "https://hmajax.itheima.net/api/register",method: "POST",data: {username: "usera_001",password: "usera_001"}}).then(result => {console.log(result)}).catch(error => {console.log(error)})

案例:获取天气预报

 

function getWeather(cityCode)   //封装获取天气函数
{myAxios({url: "https://hmajax.itheima.net/api/weather",params: {city: cityCode}}).then(result => {const weatherData = result.datafor(let k in weatherData){if(k === "data"){}else if(k === "dayForecast"){const weatherList = weatherData[k].map(item => {return`<li class="item">          <div class="date-box">            <span class="dateFormat">${item.dateFormat}</span>            <span class="date">${item.date}</span>          </div>          <img src="${item.weatherImg}" alt="" class="weatherImg">          <span class="weather">${item.weather}</span>          <div class="temp">            <span class="temNight">${item.temNight}</span>-            <span class="temDay">${item.temDay}</span>            <span>℃</span>          </div>          <div class="wind">            <span class="windDirection">${item.windDirection}</span>            <span class="windPower">&lt;${item.windPower}</span>          </div>        </li>`})document.querySelector(".week-wrap").innerHTML = weatherList.join("")}else if(k === "todayWeather"){document.querySelector(".today-weather").innerHTML = `<div class="range-box"><span>今天:</span><span class="range"><span class="weather">${weatherData[k].weather}</span><span class="temNight">${weatherData[k].temNight}</span><span>-</span><span class="temDay">${weatherData[k].temDay}</span><span>℃</span></span></div><ul class="sun-list"><li><span>紫外线</span><span class="ultraviolet">${weatherData[k].ultraviolet}</span></li><li><span>湿度</span><span class="humidity">${weatherData[k].humidity}</span>%</li><li><span>日出</span><span class="sunriseTime">${weatherData[k].sunriseTime}</span></li><li><span>日落</span><span class="sunsetTime">${weatherData[k].sunsetTime}</span></li></ul>`}else if(k === "weatherImg"){document.querySelector(`.${k}`).src = weatherData[k]}else{document.querySelector(`.${k}`).innerText = weatherData[k]}}}).catch(error => {console.log(error)})
}getWeather("110111")  //默认获取北京天气document.querySelector(".search-city").addEventListener("input", e => { //输入字符实时搜索城并返回列表myAxios({url: "https://hmajax.itheima.net/api/weather/city",params: {city: e.target.value}}).then(result => {document.querySelector(".search-list").innerHTML = result.data.map(item => {return `<li class="city-item" data-cityCode = "${item.code}">${item.name}</li>`}).join("")})
})document.querySelector(".search-list").addEventListener("click", e => {   //列表点击再次搜索if(e.target.classList.contains("city-item")){getWeather(e.target.dataset.citycode)}
})

 


http://www.ppmy.cn/server/165074.html

相关文章

3D图形学与可视化大屏:什么是材质属性,有什么作用?

一、颜色属性 漫反射颜色 漫反射颜色决定了物体表面对入射光进行漫反射后的颜色。当光线照射到物体表面时&#xff0c;一部分光被均匀地向各个方向散射&#xff0c;形成漫反射。漫反射颜色的选择会直接影响物体在光照下的外观。例如&#xff0c;一个红色的漫反射颜色会使物体在…

Linux+Docer 容器化部署之 Shell 语法入门篇 【Shell 循环类型】

文章目录 一、Shell 循环类型二、Shell while 循环三、Shell for 循环四、Shell until 循环五、Shell select 循环六、总结 一、Shell 循环类型 循环是一个强大的编程工具&#xff0c;使您能够重复执行一组命令。在本教程中&#xff0c;您将学习以下类型的循环 Shell 程序&…

【LeetCode 刷题】贪心算法(1)-基础

此博客为《代码随想录》二叉树章节的学习笔记&#xff0c;主要内容为贪心算法基础的相关题目解析。 文章目录 455.分发饼干1005.K次取反后最大化的数组和860.柠檬水找零 455.分发饼干 题目链接 class Solution:def findContentChildren(self, g: List[int], s: List[int]) -…

PostgreSQL 数据库模式基础操作

查看数据库或者使用pgAdmin或者QGIS查看PG数据库时&#xff0c;可以看到数据库名下面有一个Public&#xff0c;然后才是具体的表&#xff0c;搜索了一下&#xff0c;按照PG官网&#xff1a;https://www.postgresql.org/docs/current/ddl-schemas.html 的说明&#xff0c;这个Pu…

python属性修饰器

在 Python 中&#xff0c;属性装饰器&#xff08;property&#xff09; 是一种用于管理类属性访问的高级工具&#xff0c;它可以让你在访问或修改属性时添加自定义逻辑&#xff08;如数据验证、计算属性等&#xff09;。 1. 基础用法&#xff1a;将方法伪装成属性 property 允…

【Block总结】Shuffle Attention,新型的Shuffle注意力|即插即用

一、论文信息 标题: SA-Net: Shuffle Attention for Deep Convolutional Neural Networks 论文链接: arXiv 代码链接: GitHub 二、创新点 Shuffle Attention&#xff08;SA&#xff09;模块的主要创新在于高效结合了通道注意力和空间注意力&#xff0c;同时通过通道重排技…

在Windows下安装Ollama并体验DeepSeek r1大模型

在Windows下安装Ollama并体验DeepSeek r1大模型 Ollama在Windows下安装 Ollama官网&#xff1a;Ollama GitHub 下载Windows版Ollama软件&#xff1a;Release v0.5.7 ollama/ollama GitHub 下载ollama-windows-amd64.zip这个文件即可。可以说Windows拥抱开源真好&#xf…

本地部署DeepSeek开源多模态大模型Janus-Pro-7B实操

本地部署DeepSeek开源多模态大模型Janus-Pro-7B实操 Janus-Pro-7B介绍 Janus-Pro-7B 是由 DeepSeek 开发的多模态 AI 模型&#xff0c;它在理解和生成方面取得了显著的进步。这意味着它不仅可以处理文本&#xff0c;还可以处理图像等其他模态的信息。 模型主要特点:Permalink…