1.基础——定义json文件
{
"userinfo": [
{ "account":"15639864589" , "password":"123456789" , "email":"123456789@qq.com" },
{ "account":"15652689689" , "password":"123456789" , "email":"123456789@qq.com" },
{ "account":"15635456989" , "password":"123456789" , "email":"123456789@qq.com" },
{ "account":"15632145689" , "password":"123456789" , "email":"123456789@qq.com" }
]
}
目录如下:
2.ajax请求json jquery转换为数据字典
我们通过ajax请求该json文件的数据 将其转换为字典
//-----基础信息start
//用户信息字典
var userinfoDic = {};
$.ajax({
//请求方式为get
type:"GET",
//json文件位置
url:"./json/user.json",
//返回数据格式为json
dataType: "json",
//请求成功完成后要执行的方法
success: function(data){
//使用$.each方法遍历返回的数据date
$.each(data.userinfo,function(i,item){
//设置根据用户账号密码找用户
userinfoDic[item.account,item.password] = item;
});
}
});
//-----基础信息end
3.字典测试
//登录按钮的点击事件
$("#login").bind('click',function(){
var account = $("#account").val();
var password = $("#password").val();
//
if(account != '' && password != ''){
if(userinfoDic[account,password]){
window.location.href = 'index.html';
}else{
alert("账号或密码错误!");
}
}else{
alert("账号或密码不能为空!");
}
});