Ajax Simulation Plugin-Mockjax Introduction

Source: Internet
Author: User

In the front and back of the joint project is often encountered a scenario, we have a unified definition of the interface data format, the front and back end of each according to the interface development, the current end of the development of the backend interface has not been developed, this time to interface testing, can only wait for background development to test, There will be a lot of wasted time in the middle.

Now there is a sharp weapon to solve this problem, even without the background, as long as the data format of the interface in advance, so the front-end can be their own interface to simulate the interface test, that is Mockjax and Mockjson plug-ins.

Mockjax (Https://github.com/jakerella/jquery-mockjax) can be used to mock the specified URL, and when Ajax requests the URL, it intercepts and callbacks the fake data.

Mockjson (Https://github.com/mennovanslooten/mockJSON) is a bit like the data generater of JSON, which generates the JSON data of the callback according to the format random number we specify.

First, let's take a look at an example, assuming that we currently need to develop a Web site that uses Ajax to request/webapi/getuserdata, get the user data, and display the obtained data on the page, such as the following code:

<H1>User Data</H1>    <DivID= "Result"></Div><Scripttype= "Text/javascript">$.ajax ({URL:'/webapi/getuserdata', type:'GET', DataType:'JSON', Error:function(XHR) {alert ('unable to get information!'); }, Success:function(response) {$("#result"). Append (Response);
}});</Script>

Execute the code, we can find that this program is not successful execution, because/webapi/getuserdata does not exist, so will jump out the error message:

This time Mockjax comes in handy, and we add this code before we ask for Ajax:

$.mockjax ({    '/webapi/getuserdata ',    //  HTTP status code returned    status:200  ,    //  response time    responsetime:750,    / / HTTP content Type of response     contentType: ' Application/json ',    //  return content    responsetext: ' User information '});

This means that we mock jquery Ajax, and when using AJAX to request/webapi/getuserdata this address, it will take 750ms of time to return to status code 200 and the string "User information". Re-execute the Web page to see that the execution was successful.

Of course, in fact, the AJAX request does not just return a string, we may need JSON-formatted data. Below we rewrite the program code to request JSON data

$(function() {$.mockjax ({URL:'/webapi/getuserdata ',            //the HTTP status code returnedstatus:200,            //Response Timeresponsetime:750,            //HTTP content type of responseContentType: ' Application/json ',            //What's returnedresponsetext: $.mockjson.generatefromtemplate ({"User": [{                    "id": 1,                    "Name": "David",                    "Birthday": "2001/01/26"                }]            })        }); $.ajax ({URL:'/webapi/getuserdata ', type:' GET ', DataType:' JSON ', Error:function(XHR) {alert (' Can't get information! '); }, Success:function(response) {vardata =Response.user;  for(vari = 0; i < data.length; i++) {                    $("#result"). Append ("<ul>" + "<li>id:" + data[i].id + "</li>" + "<li>na                        Me: "+ data[i].name +" </li> "+" <li>birthday: "+ data[i].birthday +" </li> "+ "</ul>" + "                    );    }            }        }); });

Once executed, you can see that the JSON data was successfully received and displayed on the page:

What if we need a lot of data and we spend a lot of time just to get the JSON data right? At this point we need mockjson, which can generate JSON data based on the rules we make, and we modify the responsetext portion of Mockjax to produce data using Mockjson:

$.mockjson.data.user_name = [' Zhang San ', ' John Doe ', ' Harry ', ' Zhao Liu ', ' Sun Seven ', ' Zhou Ba ', ' Wu Nine ', ' Zheng Shi '];$.mockjax ({URL:'/webapi/getuserdata ',    //the HTTP status code returnedstatus:200,    //Response Timeresponsetime:750,    //HTTP content type of responseContentType: ' Application/json ',    //What's returnedresponsetext: $.mockjson.generatefromtemplate ({"User|3-6": [{        "Id|+1": 1,        "Name": "@USER_NAME",             "Birthday": "@DATE_YYYY/@DATE_MM/@DATE_DD"        }]    })});

First, we first added a custom user_name variable to the Mockjson.

I used the $.mockjson.generatefromtemplate method when I set up the ResponseText, and set the rules for the user data to produce the following,

    • Generate 3-6 user, each user has the following fields,
    • The ID increases sequentially from 1, each time +1,
    • Name produces the name in the user_name that we defined above,
    • Birthday uses Mockjson built-in date_yyyy, date_mm, and date_dd to generate random dates.

Re-executing the Web page, we can find that each time the page results are different, which can be used to simulate the query out different data

Of course, Mockjax has many other functions, such as using proxy or callback function to return the response data, modify HTTP response First class, you can go to https://github.com/jakerella/jquery-mockjax above view.

Ajax Simulation Plugin-Mockjax Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.