欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mock.js使用,进行mock数据开发

程序员文章站 2024-01-22 21:06:04
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple mock Example</title>
    <script src="http://mockjs.com/dist/mock.js"></script>
</head>
<body>
<script>
    var data = Mock.mock({
        "list|1-10":[
            {
                "id|+1":1,
                "name":"@cname"
            }
        ]
    })
    console.log(JSON.stringify(data,null,2))
</script>
</body>
</html>

运行效果:
Mock.js使用,进行mock数据开发
案例二:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random</title>
    <script src="http://mockjs.com/dist/mock.js"></script>
</head>
<body>
<script>
    var random  = Mock.Random
    var friends = ["小张","小王","小李","小陈"]
    var data = {
        email : random.email(),
        image : random.image("400*400","#00405d","#fff","Mock.js"),
        name  : random.cname(),
        url   : random.url(),
        address : random.city(),
        bestfriend : random.picker(friends)
    }
    console.log(JSON.stringify(data,null,2))
</script>
</body>
</html>

运行结果:

案例三:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://mockjs.com/dist/mock.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button type="button" id="app">点击请求</button>
<script>
    $('#app').click(function() {
        $.ajax({
            url: 'http://api.yourdomain.com/getlist/',
            type:'get',
            dataType :"json"
        }).done(function (data,status,xhr) {
            console.log(data,null,2)
        })
    })
    //定义mock数据
    var obj ={ aa : '11',bb:'22',cc:'33',dd:'44'}
    //对数据进行拦截
    Mock.mock('http://api/yourdomain.com/getlist/',{
        //定义模板语法
        "user|1-3":[
            {
                "id|+1":1,
               name:"@cname",
                "age|18-28":0,
                birthday:'@data("yyyy-MM-dd")',
                city:"@city",
                "fromobj|2":obj
            }
        ]
    })
</script>
</body>
</html>

运行结果:
TODO

相关标签: H5