Home > Web Front-end > JS Tutorial > Introduction to the principles of Mockjs

Introduction to the principles of Mockjs

零到壹度
Release: 2018-04-12 11:12:02
Original
3863 people have browsed it

The content shared with you in this article is an introduction to the principles of Mockjs. It has a certain reference value. Friends in need can refer to it

Preface

There is a project that separates the front and back ends and used Mockjs. The back end provides the data format, and the front end returns data through the simulation interface to render the page. For a while, I was puzzled about this plug-in. How to block the ajax request? I searched online and found very little information, but to no avail.
Then one day, I suddenly thought, if the ajax method request is rewritten, can this function be achieved by providing a callback before sending the request?

Ideas

  • Prepare the environment

    • ##Start with the most convenient jquery and plan to rewrite it

      $.ajax

  • The main problems that need to be solved are


    • $ .ajax is about to be rewritten, so I have to implement an xhr method for sending requests myself (I am too lazy to write the encapsulated ajax method, so I cache $.ajax for later use)

    • How to match the request address that will be intercepted

    • After intercepting the request, how to use the pre-prepared data as the data after the request is successful

  • Code implementation

    let Mock = {  // 存储匹配规则
      rules: new Map(),  // 缓存ajax方法
      ajax: $.ajax,
      mock(url, data) {
        this.rules.set(url, data)
      }
    }// 改写ajax方法$.ajax = function(options) {
      Mock.ajax({
        url: options.url,
        beforeSend(XHR) {      let data = Mock.rules.get(options.url)      // 找到规则拦截请求,并执行回调(return false时会拦截请求)
          data && options.success(data)      return !data
        },
        success(data) {      // 找不到规则,正常发送请求
          options.success(data)
        }
      })
    }// 测试Mock.mock('/a', {
      a: 1,
      b: 2})
    $.ajax({
      url: '/a',
      success(data) {
        console.log(data, 1)
      }
    })
    $.ajax({
      url: '/b',
      success(data) {
        console.log(data, 2)
      }
    })
    Copy after login

  • Function detection


    • The above code It can be copied directly to the control bar and run. We can see that only the b request is sent, and the a request is intercepted. At the same time, we can also get the expected data

    • As for Mockjs random We will not consider the function of data for now

Summary

  • After that, I also took a rough look at the Mockjs source code, and it was also rewritten. It is implemented by the

    $.ajax method of jquery and zepto. This means that if you encapsulate the ajax method with native js, it cannot be intercepted. The following is an ajax method of native js, with You can check your interest yourself:

    var Ajax={    get: function(url, fn) {
            var xhr = new XMLHttpRequest();  // XMLHttpRequest对象用于在后台与服务器交换数据          
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { // readyState == 4说明请求已完成
                    fn.call(this, xhr.responseText);  //从服务器获得数据
                }
            };
            xhr.send();
        },
        post: function (url, data, fn) {         // datat应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  // 添加http头,发送信息至服务器时内容编码类型
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {  // 304未修改
                    fn.call(this, xhr.responseText);
                }
            };
            xhr.send(data);
        }
    }
    Copy after login


The above is the detailed content of Introduction to the principles of Mockjs. 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