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
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?
Prepare the environment
$.ajax
$ .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)
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) } })
$.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!