<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录</title>
</head>
<body>
<p>账号:<input type="text" id="user"></p>
<p>密码:<input type="text" id="pass"></p>
<button id="login">登录</button>
<button id="add">注册</button>
<script src="ajax.js"></script>
<!--
接口文档
method: get
url: './data/user.php'
参数:
type = login 登录
add 注册
user = 用户名
pass = 用户密码
返回:
{err:0,msg:'登录成功'}
-->
<script>
var login = document.querySelector('#login');
var add = document.querySelector('#add');
var user = document.querySelector('#user');
var pass = document.querySelector('#pass');
login.onclick = function (){
ajax({
type: 'get',
url: './data/user.php',
data: {
type: 'login',
user: user.value,
pass: pass.value
},
success: function (data){
var json = JSON.parse(data);
if (json.err == 0){
alert(json.msg);
}
}
});
}
add.onclick = function (){
ajax({
type: 'get',
url: './data/user.php',
data: {
type: 'add',
user: user.value,
pass: pass.value
},
success: function (data){
var json = JSON.parse(data);
if (json.err == 0){
alert(json.msg);
}
}
});
}
</script>
<?php
/*
接口文档
method: get
url: './data/user.php'
参数:
type = login 登录
add 注册
user = 用户名
pass = 用户密码
返回:
{err:0,msg:'登录成功'}
*/
header('Content-Type:text/html;charset=utf-8');
$type = $_GET['type'];
$user = $_GET['user'];
$pass = $_GET['pass'];
if ($type && $user && $pass) {
//连接数据库
$link = mysqli_connect('localhost','root','xiaoming','userlist');
if(!$link){
die('连接失败:'.mysqli_connect_error());
}
//设置编码
mysqli_set_charset($link,'utf8');
//判断要登录还是要注册
// 执行sql语句
if ($type === 'login'){
$login_sql = "select * from user where username='$user' and password='$pass'";
$login_res = mysqli_query($link,$login_sql);
$login_arr = mysqli_fetch_all($login_res);
if (count($login_arr) > 0){
echo '{"err":0,"msg":"登录成功"}';
} else {
echo '{"err":-3,"msg":"账号或密码错误"}';
}
} else if($type === 'add') {
$select_sql = "select * from user where username='$user'";
$select_res = mysqli_query($link,$select_sql);
// print_r($select_res );
// die();
$select_arr = mysqli_fetch_all($select_res);
if(count($select_arr) > 0){
die('{"err":-1,"msg":"用户名已被占用"}');
} else {
$insert_sql = "insert into user (username,password) values ('$user','$pass')";
$insert_res = mysqli_query($link,$insert_sql);
if ($insert_res){
echo '{"err":0,"msg":"注册成功"}';
} else {
echo '{"err":-2,"msg":"注册失败"}';
}
}
} else {
die('{"err":-9,"msg":"参数错误"}');
}
mysqli_close($link);
} else {
echo '{"err":-9,"msg":"参数错误"}';
}
?>
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 代码:前端与数据库交互的登陆界面
发表评论 取消回复