ajax和fetch

ajax是一种无需重新加载网页的情况下,能够更新网页的技术。通过后台与服务器之间进行数据交互,ajax可以实现网页异步更新,这就意味着在不重新加载整个页面

1.原生ajax

 // 1.创建
    var xhr = new XMLHttpRequest();
    // 2.设置请求的方法和路径
    xhr.open('post', 'http://127.0.0.1:5500/abc.txt');
    // xhr.open('get','http://127.0.0.1:5501/abc.txt?username=admin&password=123456');
    // 监听后台是否返回数据

    // get和post参数有什么区别
    // get数据拼接到路径中 post可以body中的,数据安全
    // 3.发送数据
    xhr.send('username=admin&password=123456');

    // 4监听后端是否返回数据
    xhr.onreadystatechange = function () {
    
    
        if (xhr.status == 200 && xhr.readyState == 4) {
    
    
            console.log(xhr);
            console.log(xhr.status);
            console.log(xhr.readyState);
            // 判断status
            // 判断readyState

            // 5.处理数据
            var res = xhr.response;
            var h1 = document.createElement('h1');
            h1.innerHTML = res;
            document.body.appendChild(h1)
        }
    }

2.封装ajax

传入一个回调函数接收返回的数据

 function getAjax(httpUrl, callbackfn) {
    
    
        var xhr = new XMLHttpRequest()
        xhr.open('GET', httpUrl);
        xhr.send();
        xhr.onreadystatechange = function () {
    
    
            if (xhr.status == 200 && xhr.readyState == 4) {
    
    
                callbackfn(xhr)
            }
        }
    }
    // 调用这个方法
    var fn = function (xhr) {
    
    
        console.log(xhr);
        var h1 = document.createElement('h1');
        h1.innerHTML = xhr.response;
        document.body.appendChild(h1);
    }
    getAjax('http://127.0.0.1:5501/abc.txt?username=admin&password=123456', fn)

3.promise封装的ajax

promise对象,封装异步的结果
1.resolve 异步成功完成
2.reject 异步事件失败

 var httpUrl = "http://localhost:3000/articles/getOneArticle?id=1";
    var ajaxP = getAjax(httpUrl);
    function getAjax(url) {
    
    
        return new Promise(function (resolve, reject) {
    
    
            var xhr = new XMLHttpRequest();
            httpUrl = url;
            xhr.open('GET', httpUrl);
            xhr.send();
            xhr.onreadystatechange = function () {
    
    
                if (xhr.status == 200 && xhr.readyState == 4) {
    
    
                    // 处理获取得的数据
                    resolve(xhr)
                } else if (xhr.readyState == 4 && xhr.status !== 200) {
    
    
                    // 处理失败的结果
                    reject(xhr);
                }
            }
        })
    }
    ajaxP.then(function (res) {
    
    
        var result = JSON.parse(res.response);
        console.log(result);
    }).catch(function (err) {
    
    
        console.log(err);
    })

fetch

fetch就是封装好的promise
fetch是window里面的方法

 fetch(httpUrl).then(function(res){
    
    
        console.log(res);
        var result = res.json();
        result.then(function(result){
    
    
            console.log(result);
        })
    })

当遇到网络错误时,fetch返回的promise会被reject,可能是其他问题或者权限不够导致,成功的fetch不仅要包括promise被resolve,还要包括response.ok,因为http 404状态并不会认为是网络错误。
fetch中包含2个参数

  1. request对象
    一个 USVString 字符串,包含要获取资源的 URL。一些浏览器会接受 blob: 和 data: 作为 schemes.
  2. init可选配置

method: 请求使用的方法,如 GET、POST

headers: 请求的头信息,形式为 Headers 的对象或包含 ByteString 值的对象字面量

body: 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息

credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie,必须提供这个选项。

猜你喜欢

转载自blog.csdn.net/weixiwo/article/details/129485194
今日推荐