前端可用的异步请求方案

前端和后端进行数据交互的时候,主要有以下几种的异步请求方案,分别是:

①XHR —— 只能在浏览器中使用

②jQuery.ajax() —— 只能在浏览器中+jQuery中使用

③axios —— 可以在基于浏览器或Node.js的项目中使用(必需引入axios模块)

④wx.request() —— 只能在微信小程序中使用

⑤uni.request() ——只能在uni-app中使用

⑥fetch() —— HTML5标准中新提出的用于代替XHR的方案

①经典的AJAX发送给GET请求

  ①创建一个能够发起HTTP请求消息的对象
	let  xhr = new  XMLHttpRequest( )  
	//名称含义:向服务器发起HTTP请求消息,期望得到XML格式的响应数据
  ②XHR打开到服务器的连接(即拨通电话)
	xhr.open(method,  url)		//发起一个异步请求
	xhr.open(method,  url,   true)	//发起一个异步请求
	xhr.open(method,  url,   false)	//发起一个同步请求
	xhr.setRequestHeader(name,  value)	//设置一个请求消息头
  ③提前声明好:如果得到了服务器端的响应消息,该如何处理
	xhr.onload = function(){
		console.log( xhr.status )  //响应状态行中的状态,例如200/404...
		console.log( xhr.statusText )  //响应状态行中的原因短句,例如OK/NotFound
		let all = xhr.getAllResponseHeaders()  //得到所有的响应消息头部
		let value = xhr.getResponseHeader(name) //得到某一个定的响应消息头部
		let responseBody = xhr.responseText   //响应消息的主体内容   
	}
  ④向服务器端发送请求消息
	xhr.send( )		//发送一个没有请求主体的请求消息
	xhr.send( null )	//发送一个没有请求主体的请求消息
	xhr.send( 'uname=tom&upwd=123' )   //发送一个有请求主体的请求消息

AJAX发送有请求主题的请求(POST/PUT)

let req = new XMLHttpRequest()
	req.open('POST/PUT',    '/user/add?v=3&loc=beijing ')
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
	req.onload = function(){ req.responseText }
	req.send( uname=%e5%bd%e9&upwd=123&age=20 )

②jQuery.ajax()

jQuery提供了用 回调函数封装的 ajax 请求方法

// 数据接口: 利用express制作接口, 客户端发送请求可以获取数据
      const url = 'https://api.xin88.top/mooc/category_list.json'
      // $.get: 发送get请求
      // 参数1: 请求地址;   参数2: 成功后的回调函数
      $.get(url, data => {
        console.log('data:', data)

        const html = data.result.map(value => {
          const { channelName } = value

          return `<span>${channelName}</span>`
        })

        $('#box').append(html)
      })

③axios 用的比较多的一种方法

      const url = 'xxxxx'
      this.axios.get(url).then(res => {
        this.data = res.data
      })

以及axios发送POST请求

  data() {
    return {
      data: null,
      uname: '',
      pwd: '',
      re_pwd: '',
      email: '',
      phone: '',
    }
  },
  methods: {
    getData() {
      const url = 'user/register.php'
      //  发送post请求
      //   利用对象解构!
      const { uname, pwd, re_pwd, email, phone } = this
      const params = 
      `uname=${uname}&upwd=${pwd}&upwdconfirm=${re_pwd}&email=${email}&phone=${phone}`
      this.axios.post(url, params).then(res => {
        if (res.data.code == 200) {
          alert('恭喜您,成为第' + res.data.uid + '号会员!')
        } else {
          alert(res.data.msg)
        }
      })
    },
  }

 ④wx.request() 顾名思义只能在微信小程序中进行使用

wx.request({
  url: '请求地址', //仅为示例,并非真实的接口地址
  data: {
    x: '参数x',
    y: '参数y'
  },
  header: {   // 消息头
    'content-type': 'application/json' // 默认值
  },
  success: (res)=>{
    console.log(res.data)
  },
  fail: (err)=>{
  	console.log(err)      
  }
})

以及我自己用Promise封装的wx.request()请求

//传递cid和offset两个参数
loadMovies(cid, offset){
    return new Promise((resolve, reject)=>{
        wx.request({
            url: 'xxxx',
            data: {cid, offset},
            success: (res)=>{
                let movieList = res.data  // 查询结果列表
                resolve(movieList)
            }
        })    
    })
//实现复用
onLoad(){
    this.loadMovies(1, 0, (movieList)=>{
        ,,,,,,,
    })
}
//
tapNav(){
    this.loadMovies(xxxx, 0).then(movieList=>{
        ,,,,,,
    }).catch(err=>{
        ,,,,,,
    })
}

⑤uni.request() 只能在uni-app中使用的方式

	//页面加载完成时,异步请求服务器网络数据
	onLoad() {
        //加载提示开始
			uni.showLoading({
				title:"首页数据加载中,请稍后"
			}),
		uni.request({
			url:"xxxxxxxx",
			//methods:'get' 默认是get请求,可以省略
            //成功相应必须要是箭头函数,不然的话this指向会发生改变!
			success:(res) => {
				this.indexData = res.data.data
				console.log('比如这是商品列表',res.data.data)
			},
			//请求失败后的回调
			fail:(res) => {
				console.log('fail',res)
			},
			//请求完成后的回调,无论是成功还是失败
			complete:(res) => {
				console.log('请求结束',res)
                uni.hideLoading()
			}
		})
	}

⑥fetch() —— HTML5标准中新提出的用于代替XHR的方案

  // 使用fetch发起GET请求
        url = `http://wwww.xxxx.cn/login?aname=${aname}&pwd=${pwd}`
        fetch(url)
            .then(res => res.json())
            .then(data => {console.log('响应消息主体:', data)})
            //这里的catch可以捕捉两个失败,1请求的url错误,2请求的响应消息主题失败
            .catch(err => {console.log('请求失败:', err)})

使用fetch发送post请求


        let options = {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `aname=${aname}&apwd=${apwd}`//请求消息主体
        }
        fetch(url, options)
            .then(res => res.json())
            .then(data => { console.log('请求成功,且响应消息主体解析完成', data) })
            .catch(err => { console.log('请求失败或相应主体解析失败', err) })
    }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我已经明白您的需求了。 以下是我编写的用 Node.js 模拟接口的代码: ```javascript const http = require('http'); http.createServer((req, res) => { if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.write(JSON.stringify(['zs', 'ls', 'ww'])); res.end(); } else if (req.method === 'POST') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.write(JSON.stringify(['张三', '李四', '王五'])); res.end(); } }).listen(3000, () => { console.log('Server is running at http://localhost:3000'); }); ``` 以上代码创建了一个 HTTP 服务器,监听在本地的 3000 端口。当客户端发送 GET 请求时,返回 JSON 格式的 `["zs","ls","ww"]` 数组;当客户端发送 POST 请求时,返回 JSON 格式的 `["张三","李四","王五"]` 数组。 接下来,我将为您提供前端页面的 HTML 和 JavaScript 代码: ```html <input oninput="debounce(handleInput, 500)" /> <span></span> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> const input = document.querySelector('input'); const span = document.querySelector('span'); function handleInput() { const value = input.value; if (value === '') { span.textContent = ''; return; } axios.get(`http://localhost:3000?q=${value}`) .then(response => { span.textContent = '可用'; }) .catch(error => { axios.post('http://localhost:3000', { q: value }) .then(response => { span.textContent = '可用'; }) .catch(error => { span.textContent = '不可用'; }); }); } function debounce(fn, delay) { let timer; return function() { const context = this; const args = arguments; clearTimeout(timer); timer = setTimeout(() => { fn.apply(context, args); }, delay); }; } </script> ``` 以上代码中,我们首先获取了 HTML 页面中的 `input` 和 `span` 元素,然后定义了 `handleInput` 函数。该函数会在用户输入时被触发,并使用防抖函数 `debounce` 控制异步请求的频率。 在 `handleInput` 函数中,我们首先获取了用户输入的值 `value`,并判断其是否为空。如果为空,则清空 `span` 中的内容,并直接返回。 否则,我们使用 axios 发送 GET 请求,请求的 URL 中包含了用户输入的值 `value`。如果请求成功,则将 `span` 中的内容设置为“可用”。 如果 GET 请求失败,则说明该值不存在,我们使用 axios 发送 POST 请求,请求的 body 中包含了用户输入的值 `value`。如果 POST 请求成功,则将 `span` 中的内容设置为“可用”。 如果 POST 请求失败,则说明该值已经被占用,我们将 `span` 中的内容设置为“不可用”。 最后,我们使用了防抖函数 `debounce` 包装了 `handleInput` 函数,并将其作为 `input` 元素的 `oninput` 事件处理函数。这样,当用户输入时,就会触发 `debounce(handleInput, 500)` 函数,从而控制异步请求的频率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多看书少吃饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值