javascript异步请求的几种方式示例

javascript异步请求的几种方式示例

整理JS的最后一天,主要写一点ajax和fetch。记得最开始了解ajax的时候,一些文章都是结合项目来说的,一大坨,对于小白来说理解需要时间。这里仅描述核心功能,最大程度精简代码。这里用到的数据为疫情数据。

首先说为什么使用ajax

  • 在不重新加载页面的情况下更新网页
  • 在页面已加载后从服务器请求数据
  • 在页面已加载后从服务器接收数据
  • 在后台向服务器发送数据
    (忘了在哪抄的了)

1.XMLHttpRequest

ajax基于XMLHttpRequest实现,下面是原生ajax的实现方式

	const reqURL = "http://127.0.0.1:5000/"; //请求地址
        // 代理对象
    let xhr = new XMLHttpRequest();

    xhr.timeout = 5000; //最大请求时间
    xhr.responseType = "text"; //返回类型

        // 回调
    xhr.onreadystatechange = function (evt) {
        if (evt.target.readyState == 4) { //XMLHttpRequest 对象的状态会从0到4变化,当状态为4时,表示请求完成
            let res = JSON.parse(evt.target.response);
            console.log(res); //输出返回内容
            }
        }
    xhr.ontimeout = (evt) => {
        console.log("请求超时");
        }
    xhr.onerror = (evt) => {
        console.log("网络错误");
        }
    xhr.open("post", reqURL);

    query = JSON.stringify({'provinceName':'山东省','cityName':'青岛','skip':0,'n':10})
        // 发送
    xhr.send(query);

2.jquery中实现了封装过的ajax,引入jquery.min.js,基本使用方式如下

$.ajax({
            url: "http://127.0.0.1:5000/",
            data: JSON.stringify({ 'provinceName': '山东省', 'cityName': '青岛', 'skip': 0, 'n': 10 }), //发送的数据
            type: "POST",
            dataType: "json", //返回json数据
            success: function (response) {
                console.log(response);
            }, //成功回调
            error: function () {
                console.log('error');
            }
        });

效果同上

3.fetch

除了ajax,fetch同样可以实现异步请求。

get

	fetch('https://raw.githubusercontent.com/BlankerL/DXY-2019-nCoV-Data/master/json/DXYArea.json', {
            method: 'GET',
            mode: 'cors' //跨域
        })
            .then((res) => {
                return res.json()
            }) //返回json数据
            .then((res) => {
                console.log(res)
            })

post

		var url = "http://127.0.0.1:5000/";
        var data = JSON.stringify({ 'provinceName': '山东省', 'cityName': '青岛', 'skip': 0, 'n': 10 });

        fetch(url, {
            method: 'POST',
            body: data,
            headers: new Headers({
                'Content-Type': 'application/json'
            })
        }).then(res => res.json())
            .catch(error => {
                console.error('Error:', error);
            })
            .then(response => {
                console.log('Success:', response);
            });

至于其他api、参数,可以参考下面几个链接
XMLHttpRequest
jQuery
fetch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值