Home > Web Front-end > JS Tutorial > What are the methods for using ajax in Vue?

What are the methods for using ajax in Vue?

亚连
Release: 2018-06-11 14:10:16
Original
1874 people have browsed it

Below I will share with you an article about ajax public methods based on Vue (detailed explanation), which has a good reference value and I hope it will be helpful to 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 above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How classList implements two button style switching

Virtual scrolling about 2.x in vue.js Article

How to use AngularJS to implement the function of downloading excel files

How to configure config in vue (detailed tutorial)

How to implement multi-object movement in JS (detailed tutorial)

The above is the detailed content of What are the methods for using ajax in Vue?. 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