Home > Web Front-end > JS Tutorial > Detailed explanation of Vue's ajax public method instance

Detailed explanation of Vue's ajax public method instance

小云云
Release: 2018-01-24 10:23:51
Original
1546 people have browsed it

This article mainly shares an ajax public method based on Vue (detailed explanation). It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

In order to reduce the redundancy of the code, we decided to extract the public method of requesting ajax for colleagues to use.

I used ES6 syntax to write this method.

/**
  * @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);
    }
   });
  });
 }
Copy after login

Return the request result through the callback function.

The test code is as follows:

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);
    })
   }
Copy after login

The test passed!

Related recommendations:

Complete example sharing of Ajax operations in JQuery

Recommended 9 articles about public methods

C# Detailed implementation of the public method class for date format conversion

The above is the detailed content of Detailed explanation of Vue's ajax public method instance. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template