首頁  >  文章  >  web前端  >  Vue的ajax公共方法實例詳解

Vue的ajax公共方法實例詳解

小云云
小云云原創
2018-01-24 10:23:511463瀏覽

本文主要為大家分享一篇基於Vue的ajax公共方法(詳解),具有很好的參考價值,希望對大家有幫助。一起跟著小編過來看看吧,希望能幫助大家。

為了減少程式碼的冗餘,決定抽離出要求ajax的公共方法,供同事們使用。

我使用了ES6語法,寫了這個方法。

/**
  * @param type 请求类型,分为POST/GET
  * @param url 请求url
  * @param contentType
  * @param headers
  * @param data
  * @returns {Promise<any>}
  */
 ajaxData: function (type, url, contentType, headers, data) {
  return new Promise(function(resolve) {
   $.ajax({
    type: type,
    url: url,
    data: data,
    timeout: 30000, //超时时间:10秒
    headers: headers,
    success: function(data) {
     resolve(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
     resolve(XMLHttpRequest);
    }
   });
  });
 }

透過回呼函數的方式傳回請求結果。

測試程式碼如下:

getAjaxDataMethod: function () {
    const url = "";
    const type = "POST";
    const contentType = "application/json";
    const headers = {};
    const data = {};
    Api.ajaxData(type, url, contentType, headers, data).then(function (res) {
     console.log(res);
    }).catch(function (err) {
     console.log(err);
    })
   }

測試通過!

相關推薦:

JQuery中Ajax的操作完整範例分享

關於公共方法的9篇文章推薦

C#日期格式轉換的公共方法類別的實作詳解

#

以上是Vue的ajax公共方法實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn