Table of Contents
Preface
Ideas
Home Web Front-end JS Tutorial Introduction to the principles of Mockjs

Introduction to the principles of Mockjs

Apr 12, 2018 am 11:12 AM
mockjs principle

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)
      }
    })

  • 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);
        }
    }


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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
4 weeks ago By Jack chen

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

In-depth understanding of the batch Insert implementation principle in MyBatis In-depth understanding of the batch Insert implementation principle in MyBatis Feb 21, 2024 pm 04:42 PM

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

In-depth discussion of the principles and practices of the Struts framework In-depth discussion of the principles and practices of the Struts framework Feb 18, 2024 pm 06:10 PM

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

An in-depth analysis of the functions and working principles of the Linux chage command An in-depth analysis of the functions and working principles of the Linux chage command Feb 24, 2024 pm 03:48 PM

The chage command in the Linux system is a command used to modify the password expiration date of a user account. It can also be used to modify the longest and shortest usable date of the account. This command plays a very important role in managing user account security. It can effectively control the usage period of user passwords and enhance system security. How to use the chage command: The basic syntax of the chage command is: chage [option] user name. For example, to modify the password expiration date of user "testuser", you can use the following command

An in-depth discussion of the functions and principles of Linux RPM tools An in-depth discussion of the functions and principles of Linux RPM tools Feb 23, 2024 pm 03:00 PM

The RPM (RedHatPackageManager) tool in Linux systems is a powerful tool for installing, upgrading, uninstalling and managing system software packages. It is a commonly used software package management tool in RedHatLinux systems and is also used by many other Linux distributions. The role of the RPM tool is very important. It allows system administrators and users to easily manage software packages on the system. Through RPM, users can easily install new software packages and upgrade existing software

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

The basic principles and methods of implementing inheritance methods in Golang The basic principles and methods of implementing inheritance methods in Golang Jan 20, 2024 am 09:11 AM

The basic principles and implementation methods of Golang inheritance methods In Golang, inheritance is one of the important features of object-oriented programming. Through inheritance, we can use the properties and methods of the parent class to achieve code reuse and extensibility. This article will introduce the basic principles and implementation methods of Golang inheritance methods, and provide specific code examples. The basic principle of inheritance methods In Golang, inheritance is implemented by embedding structures. When a structure is embedded in another structure, the embedded structure has embedded

See all articles