Ajax applet requests were male portion

Frontiers: When we write front-end application, if the data is dynamic, and user interaction, can not help but work with data. I.e., the front end of the form by the user input background data transfer. Background Memory Database. If we need to show, requesting it to the background of the interface, and resolution. To give the corresponding data.

That is the kind of ajax to create interactive web applications web development technology. It is a without having to reload the entire web page technical section of the page can be updated. It is the underlying asynchronous XHR request and according to the state, obtained by the callback function.

Back to the topic, our small program, the background is by interacting with the Promise objects, (es6 grammar), however, the applet framework ready wx.request ({url, method, data, header, success, fail}), we can put it in the Promise object.

//向服务器请求数据
import {
  isDev
} from '../api.js';
const ajax = function(options) {
  // 是否需要loading框,默认有。
  let showLoading = options.showLoading == undefined ? true : options.showLoading

  if (showLoading) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  let headerObject = {};
  headerObject['content-type'] = options.contentType ? options.contentType : 'application/x-www-form-urlencoded;charset=UTF-8'; // application/json  application/x-www-form-urlencoded

  const token = wx.getStorageSync('token');
  const openid = wx.getStorageSync('openid')
  if (token && openid) {
    headerObject['token'] = token;
    headerObject['openid'] = openid;
  }
  const url = `${options.url}`;
  if (!options.method){
    console.log(`请求地址:${decodeURIComponent(options.url)}`);
    console.log(`请求参数:${JSON.stringify(options.data)}`);
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      method: (!options.method ? 'POST' : options.method.toUpperCase()),
      data: options.data,
      header: headerObject,
      success: function(res) {
        let resMessage = JSON.stringify(res);
        if (resMessage.length > 800) {
          resMessage = resMessage.substring(0, 800);
        }
        if (isDev !== 'PRO' && !options.method){
          console.log('返回成功结果:' + resMessage);
        }
        if (showLoading) {
          wx.hideLoading();
        }
        if (res) {
          if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 304) {
            if (res.data) {
              resolve(res.data);
            }
          } 
        }
      },
      fail: function(error) {
        if (showLoading) {
          wx.hideLoading();
        }
        console.log('返回失败结果:' + JSON.stringify(error))
        reject(error);
      }
    })
  })
}

module.exports = ajax

  Planing analysis: 

1. The introduction of the last written file api, by {isDev} to find the corresponding variable

2. Define constants ajax assign it a function, a function of expression, can be cited.

3. This function has a parameter, option is that we pass the default value. (When not pass showLoading, that is undefined allowed true, Boolean value otherwise pass), when showLoading is true, the animation is loaded with micro-channel wx.showLoading ways to reduce impatience waiting for the user.

4. define local variables empty object headerObject, content-type attribute to their default   application / x-www-form- urlencoded ( browser, native form form), there is the passed application / json (json transfer format),

5.  Page In some cases, get a page token and openid, and assigned to the object headerObject up property, and to header: headerObject, passed in the past. Define constants url, decodeURIComponent url. And to obtain data to be transmitted Data, stringified.

6. Return the default target is a post request Promise and capital requirements. resolve (res.data); successful return objects out

 

Guess you like

Origin www.cnblogs.com/liliuyu/p/11494990.html