在jQuery项目中使用mock.js
步骤1.搭建项目
步骤1.1创建项目
新建文件夹jquery-mock-demo
步骤1.2新建index.html,引入jquery.js文件和mock.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/Mock.js/1.0.0/mock-min.js"></script>
</head>
<body>
</body>
</html>
步骤2.mock和jQuery结合
步骤2.1书写mock/index.js
Mock.mock('/user/userInfo', 'get', {
id: "@id()", //得到随机的id
username: "@cname()", //随机生成中文名字
date: "@date()", //随机生成日期
avator: "@image('200x200','#50B347','#fff','avatar')", //生成图片,参数:size,background,foreground,text
description: "@paragraph()", //描述
ip: "@ip()", //IP地址
email: "@email()" //email
})
步骤2.2使用jQuery发送ajax请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/Mock.js/1.0.0/mock-min.js"></script>
</head>
<body>
</body>
<script src="./mock/index.js"></script>
<script>
$.ajax({
url: '/user/userInfo',
dataType: 'json',
success: (data) => {
console.log(data)
}
})
</script>
</html>
步骤3 移除Mock
通过添加全局变量ENV来判断
步骤3.1 修改index.html文件,增加全局变量ENV
步骤3.2 修改index.js文件:
增加if判断
步骤3.3 重新打开网页验证是否可以获取到mock服务器返回给前端的数据
步骤3.4 将全局变量MOCK的值改为false,再次验证:
发现无法访问到mock响应的数据,说明mockjs移除成功!!!