Ajax,fetch方法

簡單封裝了一個ajax的方法:


       ajax({
            url: "test.txt", //請求地址
            type: "get",   //請求方式
            data: {"name": "Tom"}, //請求參數(shù)
            async: true,   //是否異步
            success: function (response) {
                console.log(response);   //   此處執(zhí)行請求成功后的代碼
            },
            fail: function (status) {
                console.log('狀態(tài)碼為'+status);   // 此處為執(zhí)行成功后的代碼
            }

        });

        function ajax(options) {
            var url = options.url || "";
            var type = (options.type || "GET").toUpperCase();
            var data = options.data || {};
            var async = options.async || true;

            var params = pieceParams(data);

            var xhr = new XMLHttpRequest()

            xhr.onreadystatechange = (function (myxhr) {
                return function () {
                    if (myxhr.readyState === 4 && myxhr.status === 200) {
                        options.success(myxhr.responseText)
                    } else {
                        options.fail(myxhr.status)
                    }
                }
            })(xhr)
            if (type === "GET") {
                xhr.open("GET", url + "?" + params, async)
                xhr.send()
            } else if (type === "POST") {
                xhr.open("post", url, async)
                xhr.setRequestHeader("Content-Type", "application/application/x-www-form-urlencoded")
                xhr.send(params)
            }
        }

        //處理參數(shù)
        function pieceParams(data) {
            var arr = []
            for (var i in data) {
                arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]))
            }
            arr.push("randomNum=" + Date.now())
            return arr.join("&")
        }

使用fetch來發(fā)起獲取資源的請求:

fetch(input, init).then(function(response) { ... });

參數(shù)
?input
定義要獲取的資源。這可能是:一個 USVString
字符串,包含要獲取資源的 URL。
一個 Request
對象。
init (可選)
一個配置項對象,包括所有對請求的設(shè)置??蛇x的參數(shù)有:

  • method: 請求使用的方法,如 GET、POST。
  • headers: 請求的頭信息,形式為 Headers
    對象或 ByteString
    。
  • body: 請求的 body 信息:可能是一個 Blob
    BufferSource
    、FormData
    、URLSearchParams
    或者 USVString
    對象。注意 GET 或 HEAD 方法的請求不能包含 body 信息。
  • mode: 請求的模式,如 cors、 no-cors 或者 same-origin。
  • credentials: 請求的 credentials,如 omit、same-origin 或者include。
  • cache: 請求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached.

get請求:

fetch("/test.json").then(function(res) {
  if (res.ok) { //當(dāng)status為2xx的時候它是true
    res.json().then(function(data) {
      console.log(data);
    });
  } else {
    console.log("未能正確響應(yīng):", res.status);
  }
}, function(e) {
  console.log("Fetch failed!", e);
});

post請求:

fetch("http://www.example.org/submit.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  body: "firstName=Nikhil&favColor=blue&password=easytoguess"
}).then(function(res) {
  if (res.ok) {
    alert("Perfect! Your settings are saved.");
  } else if (res.status == 401) {
    alert("Oops! You are not authorized.");
  }
}, function(e) {
  alert("Error submitting form!");
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • JavaScript 通過XMLHttpRequest(XHR)來執(zhí)行異步請求,這個方式已經(jīng)存在了很長一段時間。雖...
    Bruce_zhuan閱讀 2,552評論 1 10
  • 導(dǎo)讀 傳遞信息到服務(wù)器,從服務(wù)器獲取信息,是前端發(fā)展的重中之重,尤其是現(xiàn)在前后端分離的大前提下,前后端的數(shù)據(jù)交互是...
    Chris_dc閱讀 2,258評論 1 9
  • Asynchronous JavaScript and XML(異步的 JavaScript 和 XML) XHR...
    KeKeMars閱讀 2,917評論 1 2
  • 今天小別墅甚是熱鬧,因為書友如意要去澳大利亞旅游。大家都替若兒開心,但是也覺得有點兒舍不得,于是紛紛作詩相送! ...
    sujing123閱讀 606評論 0 3

友情鏈接更多精彩內(nèi)容