Ajax的封裝。

來源:互聯網
上載者:User

標籤:params   hang   content   send   response   ajax   服務端   調用   pre   

封裝 Ajax

因為Ajax 使用起來比較麻煩,主要就是參數問題,比如到底使用GET 還是POST;到

底是使用同步還是非同步等等,我們需要封裝一個Ajax 函數,來方便我們調用。

   封裝支援接收來自服務端的資料,不可以發送資料到服務端

/*** 此封裝只支援接收來自服務端的資料,不可以發送資料到服務端 */function ajax(obj) {    var xhr = new XMLHttpRequest();    obj.url = obj.url + ‘?rand=‘ + Math.random();    xhr.open(obj.method, obj.url, obj.async);    xhr.send(null);    if (obj.async === false) {        callback();    }    if (obj.async === true) {        xhr.onreadystatechange = function () {            if (xhr.readyState == 4) {                callback();            }        };    }    function callback () {        if (xhr.status == 200) {            obj.success(xhr.responseText); //回調        } else {            alert(‘資料返回失敗!狀態碼:‘ + xhr.status + ‘,狀態資訊:‘ + xhr.statusText);        }    }}

  

   把上面的代碼封裝在ajax2.js中,在頁面上引入該檔案。

<!DOCTYPE html><html><head>    <title>Ajax的封裝</title>    <meta charset="utf-8">    <script src="ajax2.js"></script></head><body><button id="btn">調用Ajax</button><script>    document.getElementById("btn").onclick=function(){        ajax({            method : ‘get‘,            url : ‘http://localhost:3000/api/2‘,            success : function (text) {                alert(text);            },            async :false        });    };</script></body></html>7.2  封裝支援接收來自服務端的資料,又可以發送資料到服務端function ajax(obj) {    var xhr = new XMLHttpRequest();    obj.url = obj.url + ‘?rand=‘ + Math.random();    obj.data = params(obj.data);    if (obj.method === ‘get‘) {        obj.url = obj.url.indexOf(‘?‘) == -1 ? obj.url + ‘?‘ + obj.data : obj.url + ‘&‘ + obj.data;    }     if (obj.async === true) {        xhr.onreadystatechange = function () {            if (xhr.readyState == 4) {                callback();            }        };    }    xhr.open(obj.method, obj.url, obj.async);    if (obj.method === ‘post‘) {        xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);        xhr.send(obj.data);    } else {        xhr.send(null);    }    if (obj.async === false) {        callback();    }    function callback () {        if (xhr.status == 200) {            obj.success(xhr.responseText); //回調        } else {            alert(‘資料返回失敗!狀態碼:‘ + xhr.status + ‘,狀態資訊:‘ + xhr.statusText);        }    }} //名值對編碼function params(data) {    var arr = [];    for (var i in data) {        arr.push(encodeURIComponent(i) + ‘=‘ + encodeURIComponent(data[i]));    }    return arr.join(‘&‘);}

          希望能夠幫到你!

Ajax的封裝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.