Home  >  Article  >  php教程  >  Use mock.js to make front-end development independent of back-end

Use mock.js to make front-end development independent of back-end

高洛峰
高洛峰Original
2016-11-22 12:35:461633browse

Function implemented by Mock.js.

Generate data based on data templates.

Generate data based on HTML template.

Intercept and simulate Ajax requests.

This article only demonstrates using mock.js to simulate and intercept Ajax requests.

First of all, quote in the page:

<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script src="http://mockjs.com/dist/mock.js"></script>

Define DIV:

<div>
    <h1 id="mockjs">mockjs</h1>
</div>

The JS code is as follows:

<script type="text/javascript">

    //调用mock方法模拟数据
    Mock.mock(
        &#39;http://mockjs&#39;, {
            "userName" : &#39;@name&#39;,     //模拟名称
            "age|1-100":100,          //模拟年龄(1-100)
            "color"    : "@color",    //模拟色值
            "date"     : "@date(&#39;yyyy-MM-dd&#39;)",  //模拟时间
            "url"      : "@url()",     //模拟url
            "content"  : "@cparagraph()" //模拟文本
        }
    );
    
    //ajax请求
    $("#mockjs").click(function(){
        $.ajax({
            url        : "http://mockjs",    //请求的url地址
            dataType   : "json",   //返回格式为json
            async      : true, //请求是否异步,默认为异步,这也是ajax重要特性
            data       : {},    //参数值
            type       : "GET",   //请求方式
            beforeSend : function() {
                //请求前的处理
            },
            success: function(req) {
                //请求成功时处理
                console.log(req);
            },
            complete: function() {
                //请求完成的处理
            },
            error: function() {
                //请求出错处理
            }
        });
    });
</script>

The running rendering is as follows:

Use mock.js to make front-end development independent of back-end

You can see from the above rendering that the data is different every time.

If you want to know more Mock commands, you can check out the Mock.js official website: http://mockjs.com/

The above is just an introduction.

In order to make system management and use more convenient, everyone can learn about Ali RAP.

RAP is a visual interface management tool that analyzes the interface structure, dynamically generates simulation data, verifies the correctness of the real interface, and improves our collaboration efficiency through a series of automated tools around interface definition. Our slogan: Be more efficient and get home for dinner!


Statement:
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