Home > Web Front-end > JS Tutorial > Detailed example of jQuery Mockjax plug-in simulating Ajax requests_jquery

Detailed example of jQuery Mockjax plug-in simulating Ajax requests_jquery

WBOY
Release: 2016-05-16 15:20:37
Original
1282 people have browsed it

1. Principle

jquery-mockjax is used to mock the return data of the front-end ajax request to the background.

The principle is very simple

Put a breakpoint in your js code where you want to send an ajax request, and then compare the value of $.ajax.toString() when [jquery-mockjax is introduced] and [jquery-mockjax is not introduced].

Obviously, when jquery-mockjax is introduced, this mock library will replace the ajax function provided by jquery. This makes it easy to mock.

In the actual development process, the front-end and back-end negotiated a unified interface, and then each started their own tasks. At this time, I have such an Ajax request that needs to get data from the background:

$.ajax({
url: '/products/'
}).done(function(res) {
$('#result').html(res);
}); 
Copy after login

But this service may not have been created yet. Maybe the guy who developed the backend (those handsome guys who use PHP, Ruby, .NET, GoldFusion, etc.) has deserted, or maybe he is busy with other things. Anyway, when this request is made I don't get the results I want, I just get a 404 (Not Found) error.

This is really bad, and urging is useless. The testers next to me are clamoring to test it, and I am eager to see immediate results. At this time, you can only rely on yourself. One of the better methods is to simulate Ajax requests. Here I use the jQuery Mockjax plug-in.

Address: jQuery Mockjax

This is a jQuery plug-in. When you download it and quote it, place it after jQuery:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="result"></div>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="vendor/jquery.mockjax.js"></script>
</body>
</html> 
Copy after login

Then execute the code to simulate the request before the request code, use the $.mockjax() method provided by the plug-in, and temporarily specify the two parameters url and responseText:

$.mockjax({
url: '/products/',
responseText: 'Here you are!'
}); 
Copy after login

It will monitor Ajax requests with the same URL and intercept and simulate the response when the request is issued. The value of responseText is the simulated response content, so that my program can be executed happily. The running result of the first example is 'Here you are' This content will be displayed in div#result. When I no longer need to mock the request, I can use the $.mockjax.clear() method to clear it:

$.mockjax.clear();

Once the background service development is completed, I can use this method to clear all simulated requests and experience the real request effect. If you do not want to clear all simulation requests at once, but instead target a certain simulation request, you can pass in the ID of the simulation request, and each simulation request will return an ID value:

var idOne = $.mockjax({ }),
idTwo = $.mockjax({ });
$.mockjax.clear(idTwo); 
Copy after login

This clears the second simulation request and retains the first one.

Since the url address of the Ajax request must correspond to the url of the simulated request, assuming there are many requests on the page, it will be very painful to simulate each request. Fortunately, the url parameter of the plug-in provides a wildcard * Method:

$.mockjax({
url: '/books/*'
}); 
Copy after login

In addition to matching requests with the url address /books/cook, you can also match requests with the address /books/math and more. You can even use regular expressions for more complex matching patterns:

$.mockjax({
url: /^\/data\/(cook|math)$/i
}); 
Copy after login

Use the data parameter of the plug-in to perform different simulated responses based on different request data:

$.mockjax({
url: '/books/',
data: {
type: 'cook'
},
responseText: 'You want a cook book!'
});
$.mockjax({
url: '/books/',
data: {
type: 'math'
},
responseText: {
"content": "You want a math book!"
}
}); 
Copy after login

Even for the same URL address, the response content obtained is different when the requested data is different. In addition to plain text strings, the response content can also use json
Format string.

The plug-in also provides a default parameter setting object $.mockjaxSettings. Parameters that are not specified will use these default values:

$.mockjaxSettings = {
logging: true,
status: 200,
statusText: "OK",
responseTime: 500,
isTimeout: false,
throwUnmocked: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
}; 
Copy after login

After modifying the default value, subsequent simulation requests will use the modified value:

$.mockjaxSettings.contentType = "application/json"; 
Copy after login

Only the default value of contentType is modified here.

The above explains the relevant knowledge of jQuery Mockjax plug-in to simulate Ajax requests through examples. I hope it will be helpful to everyone.

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