Home > Article > Backend Development > How to write login using ajax
This articleIntroductionHow to use ajax to write login
The full name of AJAX is Asynchronous JavaScript and XML (asynchronous JavaScript and XML).
Advantages of ajax:
1. The biggest point is that the page does not refresh, and the user experience is very good.
2. Use asynchronous mode to communicate with the service server, which has a faster response capability. .
3. You can transfer some of the work previously burdened by the server to the client, using the client's idle capacity to process it, reducing the burden on the server and bandwidth, and saving space and broadband rental costs. And to reduce the burden on the server, the principle of ajax is to "fetch data on demand", which can minimize the burden on the server caused by redundant requests and responses.
4. Based on standardized and widely supported technology, there is no need to download plug-ins or small programs.
5. Ajax can make Internet applications programs smaller, faster, and more friendly.
Here I use ajax to write a simple login page: the first thing used is the database login table.
The following is the code of the login page. First, jquery must be introduced 包
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script src="jquery-3.1.1.min.js"></script> /*引入jquery包*/ </head> <body> <h2>登录页面</h2> <p>用户名:<input type="text" id="uid"/></p> <p>密码:<input type="text" id="pwd"/></p> <p><input type="button" id="btn"value="登录"/></p>11</body>12</html>
The login page is very simple, so I won’t show the picture above. I have written about it many times in previous blogs
Then the following is how to write ajax
<script type="text/javascript"> $("#btn").click(function(){ //第一步:取数据,这里用到了用户名和密码 var uid=$("#uid").val(); var pwd=$("#pwd").val(); //第二步:验证数据,这里需要从数据库调数据,我们就用到了ajax $.ajax({ url:"dlchuli.php",//请求地址 data:{uid:uid,pwd:pwd},//提交的数据 type:"POST",//提交的方式 dataType:"TEXT", //返回类型 TEXT字符串 JSON XML success:function(data){ //开始之前要去空格,用trim() if(data.trim()=="OK") { window.location.href = "main.php"; } else{ alert("用户名或者密码错误"); } } }) }) </script>## The code of #dlchuli.php is written as follows:
<?php include("DADB.class.php"); $db=new DADB(); $uid=$_POST["uid"]; $pwd=$_POST["pwd"]; $sql="select password from login where username='{$uid}'"; $arr=$db->Query($sql); if($arr[0][0]=$pwd && !empty($pwd)) { echo"OK"; } else{ echo"NO"; } ?>After writing this, the simple login page written with ajax is completed. The biggest advantage is that if an error occurs, an error will be reported on the original page and will not jump to other pages. Page
The above is the detailed content of How to write login using ajax. For more information, please follow other related articles on the PHP Chinese website!