须要完成的工做:利用mock js随机生成数据,经过ajax请求,获取这些数据并展现在网页中。css
官方文档中,Mock.mock( ),能够说是mock的精髓所在。html
Mock.mock( rurl?, rtype?, template|function( options ) )
根据数据模板生成模拟数据。ajax
-rurl:当拦截到匹配rurl的Ajax请求时,根据数据模板template生成模拟数据,做为响应数据返回。
-rtype:表示须要拦截的ajax请求类型,好比get、post、put、delete等。json
//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); //生成模拟数据
点击按钮,获取数据,并对HTML元素进行操做app
//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); } }) });
采用了两种方法,一种是直接在js中写入HTML,包括元素、内容等,另外一种是克隆HTML模板,而后对其添加内容。推荐使用方法二,便于修改调试,符合内容、样式、数据分离的规则。ide
//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); }) }