在这里,我们将给大家分享关于Mockjs+Ajax实践的知识,让您更了解mockjsreact的本质,同时也会涉及到如何更有效地ajax和mock数据、Ajax技术一ajax提交表单jqueryaja
在这里,我们将给大家分享关于Mockjs+Ajax实践的知识,让您更了解mockjs react的本质,同时也会涉及到如何更有效地ajax 和 mock 数据、Ajax 技术一 ajax提交表单 jquery ajax教程 js ajax、ajax(三) ajax提交表单、ajax实现文件上传、Ajax实例:原生js+thinkphp+ajax的内容。
本文目录一览:- Mockjs+Ajax实践(mockjs react)
- ajax 和 mock 数据
- Ajax 技术一 ajax提交表单 jquery ajax教程 js ajax
- ajax(三) ajax提交表单、ajax实现文件上传
- Ajax实例:原生js+thinkphp+ajax
Mockjs+Ajax实践(mockjs react)
需要完成的工作:利用mock js随机生成数据,通过ajax请求,获取这些数据并展示在网页中。
一 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></p> <button>点我请求ajax</button> <article> <!--<a href=""> <p></p> <img src="" alt=""> </a> --> </article> <articleid="module"> <a href=""> <p></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,jqXHR); //ajax请求成功,执行这些操作 },error:function(req,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,jqXHR){ let father = $('.temp'); $.each(data.list,function(index,obj){ //根据mock数据(temp)生成内容 //直接写入html let block = '<a href="'+ obj.thumb +'">' + '<p>'+ obj.title +'</p>' + '<img src="'+ obj.image +'" alt="我是图片">' +'</a>' father.append(block); }) } //方法二 function fillTemplet(data,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); }) }
ajax 和 mock 数据
ajax
ajax是一种技术方案,但并不是一种新技术。它依赖的是现有的CSS/HTML/Javascript,而其中最核心的依赖是浏览器提供的XMLHttpRequest对象,是这个对象使得浏览器可以发出HTTP请求与接收HTTP响应。 实现在页面不刷新的情况下和服务端进行数据交互。
作用:
传统的网页(不使用ajax)。如果需要更新内容,必须重新加载整个网页,而通过使用ajax可以在后台与服务器进行少量数据交换,可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
实现方式
- XMLHttpRequest对象
- fetch(兼容性不如XMLHttpRequest)
兼容性查询
范例
GET 范例
//异步GET var xhr = new XMLHttpRequest() xhr.open(‘GET‘,‘/login?username=evenyao&password=123‘,true) //get类型 数据需要拼接成url放到?后面 xhr.send() console.log(‘readyState:‘,xhr.readyState) xhr.addEventListener(‘readystatechange‘,function(){ //或者使用xhr.onload = function() //查看readyState状态 console.log(‘readyState:‘,xhr.readyState) }) xhr.addEventListener(‘load‘,function(){ console.log(xhr.status) if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ var data = xhr.responseText console.log(data) }else{ console.log(‘error‘) } }) xhr.onerror = function(){ console.log(‘error‘) } //等同代码 var xhr = new XMLHttpRequest() xhr.open(‘GET‘,true) xhr.send() xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ console.log(xhr.responseText) }else{ console.log(‘error‘) } } } xhr.onerror = function(){ console.log(‘error‘) }
POST 范例
//异步POST var xhr = new XMLHttpRequest() xhr.open(‘POST‘,‘/login‘,true) //post拼接数据放掉send里面 //post拼接数据放掉send里面 xhr.send(makeUrl({ username:‘evenyao‘,password:‘123‘ })) xhr.addEventListener(‘load‘,function(){ console.log(xhr.status) if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ var data = xhr.responseText console.log(data) }else{ console.log(‘error‘) } }) xhr.onerror = function(){ console.log(‘error‘) } //makeUrl拼接函数 function makeUrl(obj){ var arr = [] for(var key in obj){ arr.push(key + ‘=‘ + obj[key]) } return arr.join(‘&‘) }
封装 ajax
//封装 ajax function ajax(opts){ var url = opts.url //如果有类型就使用用户输入的类型; 如果没有,默认为后面的 var type = opts.type || ‘GET‘ var dataType = opts.dataType || ‘json‘ var onsuccess = opts.onsuccess || function(){} var onerror = opts.onerror || function(){} var data = opts.data || {} //data序列化 var dataStr = [] for(var key in data){ dataStr.push(key + ‘=‘ + data[key]) } dataStr = dataStr.join(‘&‘) //GET类型 使用url拼接 if(type === ‘GET‘){ url += ‘?‘ + dataStr } //XMLHttpRequest对象创建 var xhr = new XMLHttpRequest() xhr.open(type,url,true) xhr.onload = function(){ if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ //成功 //如果返回的数据类型是json,就解析成json格式 if(dataType === ‘json‘){ onsuccess(JSON.parse(xhr.responseText)) }else{ onsuccess(xhr.responseText) } }else{ onerror() } } //如果断网,也会执行onerror() xhr.onerror = onerror() //POST类型 if(type === ‘POST‘){ xhr.send(dataStr) }else{ xhr.send() } } ajax({ url:‘http://xxx‘,type: ‘POST‘,data: { city: ‘北京‘ },onsuccess: function(ret){ console.log(ret) render(ret) },onerror: function(){ console.log(‘服务器异常‘) showError() } }) function render(json){ } function showError(){ }
参考
你真的会使用XMLHttpRequest吗?
Ajax状态值及状态码
关于如何mock数据
http-server
本地使用http-server
node工具启动一个静态服务器
以下是已经写好的ajax用法,这里采用GET类型,使用xhr.open(‘GET‘,‘/hello2.json‘,true)
在已经安装好node
和http-server
的情况下,先cd
到对应的文件夹。然后通过http-server
启动本地server。
通过访问127.0.0.1:8080/indexl.html
,并进入控制台,即可看到mock结果
具体ajax用法代码:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width,initial-scale=1.0"> <Meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script type="text/javascript"> // ajax GET var xhr = new XMLHttpRequest() xhr.open(‘GET‘,‘/hello2.json‘,true) xhr.send() xhr.onload = function(){ console.log(xhr.status) if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ var data = xhr.responseText console.log(data) console.log(JSON.parse(data)) }else{ console.log(‘error‘) } } xhr.onerror = function(){ console.log(‘error‘) } </script> </body> </html>
模拟接口的json文件内容:
//hello2.json 内容 { "name": "go","success": true,"data": [ "70","80","90","年代" ] }
github
在github上面写一个服务器进行mock
具体和本地区别不大,只是需要注意模拟接口的地址,因为域名是github.com,所以前面还需要加项目名,详情见github/mocktest里面的README.md
测试:
github pages
线上mock
使用easy-mock.com进行mock数据
-
进入easy-mock.com,登录注册账号之后进入创建项目,输入名称然后创建