Ajax,fetch方法

2017-03-02  本文已影响0人  幸福镰刀

简单封装了一个ajax的方法:


       ajax({
            url: "test.txt", //请求地址
            type: "get",   //请求方式
            data: {"name": "Tom"}, //请求参数
            async: true,   //是否异步
            success: function (response) {
                console.log(response);   //   此处执行请求成功后的代码
            },
            fail: function (status) {
                console.log('状态码为'+status);   // 此处为执行成功后的代码
            }

        });

        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)
            }
        }

        //处理参数
        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来发起获取资源的请求:

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

参数
�input
定义要获取的资源。这可能是:一个 USVString
字符串,包含要获取资源的 URL。
一个 Request
对象。
init (可选)
一个配置项对象,包括所有对请求的设置。可选的参数有:

get请求:

fetch("/test.json").then(function(res) {
  if (res.ok) { //当status为2xx的时候它是true
    res.json().then(function(data) {
      console.log(data);
    });
  } else {
    console.log("未能正确响应:", 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!");
});
上一篇 下一篇

猜你喜欢

热点阅读