Mockjs+Ajax实践

需要完成的工作:利用mock js随机生成数据,通过ajax请求,获取这些数据并展示在网页中。

clipboard.png

一 mock js随机生成数据

官方文档中,Mock.mock( ),可以说是mock的精髓所在。

Mock.mock( rurl?, rtype?, template|function( options ) )

根据数据模板生成模拟数据。

-rurl:当拦截到匹配rurl的Ajax请求时,根据数据模板template生成模拟数据,作为响应数据返回。
-rtype:表示需要拦截的ajax请求类型,比如get、post、put、delete等。

//js部分

var testPath = '/born',     //匹配ajax操作的路径
    testMethod = 'get';     //匹配ajax请求类型

let temp = {
    'list|5-10': [{
        'aid|+1': 1,
        'title|1-6': '我是标题 ',  //30字以内的标题
        'update_time|10000-99999':10000,
        'thumb':'@URL',     //随机url地址
        'color'    : '@color', //随机颜色
        'image':'@IMAGE("200x100")' //尺寸为200*100的图片
    }]
}

Mock.mock(testPath, testMethod, temp); //生成模拟数据

二 Ajax操作

点击按钮,获取数据,并对HTML元素进行操作

//HTML部分
    <h3>==测试·准备请求ajax·测试==</h3>

    <p class="p"></p>
    <button>点我请求ajax</button>

    <article class="temp">
       <!--<a href="">
            <p class="title"></p>
            <img src="" alt="">
       </a>    -->
    </article>

    <article class="hide" id="module">
        <a href="">
            <p class="title"></p>
            <img src="" alt="">
        </a>
    </article>


//Ajax请求处理

$("button").bind('click',function(){
    $.ajax({
        url: testPath,
        type: 'get',
        dataType: 'json',
        timeout: 1000,
        success:function(data, status, jqXHR){
            fillTemplet(data, status, jqXHR);  //ajax请求成功,执行这些操作
        },
        error:function(req,status,err){
            console.log('some err')
        console.log('req',req);
        console.log('status',status);
        console.log('err',err);
        }
    })
});

三 DOM操作

采用了两种方法,一种是直接在js中写入HTML,包括元素、内容等,另一种是克隆HTML模板,然后对其添加内容。推荐使用方法二,便于修改调试,符合内容、样式、数据分离的规则。

//js部分

//方法一
function fillTemplet(data, status, jqXHR){
    let father = $('.temp');

    $.each(data.list,function(index,obj){

        //根据mock数据(temp)生成内容
        //直接写入html
        let block = '<a href="'+ obj.thumb +'">'
                    + '<p class="title">'+ obj.title +'</p>'
                    + '<img src="'+ obj.image +'" alt="我是图片">'
                    +'</a>'

        father.append(block);
    })
}

//方法二
function fillTemplet(data, status, jqXHR){
    let father = $('.temp');

    $.each(data.list,function(index,obj){
        //方法二,克隆HTML中写好的module模板
        let child = $('#module').clone().removeAttr('id').removeClass('hide');
        child.children('a').attr('href',obj.thumb);
        child.find('p').text(obj.title).css('color',obj.color);
        child.find('img').attr('src',obj.image);
        father.append(child);
    })
}
原文地址:https://www.cnblogs.com/twodog/p/12140165.html