ajax實現異步傳輸


對於ajax實現異步數據傳輸,需要以下步驟:

  1.創建XmlHttpRequest對象

var xhr = new XMLHttpRequest();

 

  2.創建一個新的HTTP請求

  

/*
* 規定請求的類型、URL 以及是否異步處理請求。
* open(method,url,async)  
* method:請求的類型;GET 或 POST
* url:文件在服務器上的位置
* async:true(異步)或 false(同步)
*/
例://get方式
   xmlhttp.open("GET","ajax_info.txt",true);
   //post方式發送數據需要設置請求頭
   xmlhttp.open("post","test.php",true)
   xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

 

  3.發送HTTP請求

XMLHttpRequest.send(data); //data是個可選參數

 

  4.設置響應http請求狀態變化的函數,設置獲取服務器返回數據的代碼語句

 

  XMLHttpRequest的五種狀態

  發送HTTP請求的目的是為了接收從服務器中返回的數據。從創建XMLHttpRequest對象開始,到發送數據、接收數據、XMLHttpRequest對象一共會經歷以下5種狀態。

  0:未初始化狀態。在創建完XMLHttpRequest對象時,該對象處於未初始化狀態。
  1:初始化狀態。在創建完XMLHttpRequest對象后使用open()方法創建了HTTP請求時,該對象處於初始化狀態,還沒有調用send()
  2:發送數據狀態。在初始化XMLHttpRequest對象后,使用send()方法發送數據時,該對象處於發送數據狀態。
  3:接收數據狀態。Web服務器接收完數據並進行處理完畢之后,向客戶端傳送返回的結果。此時,XMLHttpRequest對象處於接收數據狀態。
  4:完成狀態。XMLHttpRequest對象接收數據完畢后,進入完成狀態,此時XMLHttpRequest對象的readyState屬性值為4。此時接收完畢后的數據存入在客戶端計算機的內存中,可以使用responseText屬性或responseXml屬性來獲取數據。
  只有在XMLHttpRequest對象完成了以上5個步驟之后,才可以獲取從服務器端返回的數據。因此,如果要獲得從服務器端返回的數據,就必須要先判斷XMLHttpRequest對象的狀態。

  HTTP狀態碼

  200:請求成功

  400:客戶端請求語法錯誤,服務端無法理解信息

  404:服務器無法根據用戶請求找到相應的資源,例如URL等等

  500:服務器內部錯誤

 

當readyState=4並且狀態碼是200的時候,就表示響應已經就緒:

 xmlHttpRequest.onreadystatechange = getData;

    //定義函數
    function getData() {
        //判斷XMLHttpRequest對象的readyState屬性值是否為4,如果為4表示異步調用完成
        if (xmlHttpRequest.readyState == 4) {
            //如果HTML文件不是在Web服務器上運行,而是在本地運行,則xmlHttpRequest.status的返回值為0。因此,如果該文件在本地運行,則應該加上xmlHttpRequest.status == 0的判斷
            if (xmlHttpRequest.status == 200 || xmlHttpRequest.status == 0) { 
                document.write(xmlHttpRequest.responseText); //將返回結果以字符串形式輸出
            }
        }
    }

 

  5.獲取返回的數據:(獲取返回的數據有多種方式,get,post,Ajax)

下面是Ajax的方法:

function ajax(options) {
        //存儲默認值
        var defaults = {
            type: 'get',
            url: '',
            data: {},
            header: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function () {},
            error: function () {}
        }

        //使用options對象中的屬性覆蓋defaults對象中的屬性
        Object.assign(defaults, options);

        var xhr = new XMLHttpRequest();

        var params = '';
        //循環用戶傳遞進來的對象格式參數
        for (var attr in defaults.data) {
            //將參數轉化為字符串格式
            params += attr + '=' + defaults.data[attr] + '&'
        }
        //將參數最后的&截取掉
        params = params.substr(0, params.length - 1)

        //判斷請求方式
        if (defaults.type == 'get') {
            defaults.url = defaults.url + '?' + params
        }

        xhr.open(defaults.type, defaults.url);

        //如果請求方式為post
        if (defaults.type == 'post') {
            //請求參數類型
            var ContentType = defaults.header['Content-Type']
            xhr.setRequestHeader('Content-Type', ContentType);
            if (ContentType == 'application/json') {
                //傳遞json數據格式
                xhr.send(JSON.stringify(defaults.data))
            } else {
                //傳遞字符串拼接格式
                xhr.send(params)
            }
        } else {
            xhr.send();
        }

        xhr.onload = function () {
            //獲取響應頭數據
            var contenTtype = xhr.getResponseHeader('Content-Type')

            //服務器端返回的數據
            var responseText = xhr.responseText

            //判斷是否包含application/json
            if (contenTtype.includes('application/json')) {
                //將json字符串轉化為json對象
                responseText = JSON.parse(responseText)
            }

            //判斷是否成功
            if (xhr.status == 200) {
                defaults.success(responseText, xhr);
            } else {
                defaults.error(responseText, xhr)
            }
        }
}

//get方式
    ajax({
        url: 'http://localhost:3000/top/album?offset=0&limit=3',
        type: 'GET',
        dataType: 'json',
        success: function (data, xhr) {
            console.log(data, xhr)
        },
})

//post方式
ajax({
        url: 'http://localhost:3000/top/album',
        type: 'POST',
        data: {
            offset: 0,
            limit: 3
        },
        dataType: 'json',
        success: function (data, xhr) {
            console.log(data, xhr)
        },
    })

 

  操作獲取數據

 <div class="container">
        <p id="list"></p>
 </div>

var xhr = new XMLHttpRequest();
    xhr.open("get",
        "http://localhost:3000/search/hot",
        true);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.status == 200 && xhr.readyState == 4) {
            var res = xhr.responseText;
            // 將res轉換為json對象
            var lists = eval("(" + res + ")").result.hots;
            var data =(new Function("","return "+res))();
            
            console.log(lists)
            for (i = 0; i < 10; i++) {
                var dom = `<div class="songname">${lists[i].first}</div>`
                $("#list").append(dom)
            }
        }
}

//jquery
$.ajax({
        url: 'http://localhost:3000/top/album?offset=0&limit=3',
        type: 'GET',
        dataType: 'json',
        success: function (result) {
            var lists = result.monthData;
            for (i = 0; i < 10; i++) {
                console.log(lists[i].name);
                dom = `<div class = "songname">${lists[i].name}</div>`
                $("#list").append(dom)
            }
        }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM