Home Backend Development PHP Tutorial How to implement AJAX non-refresh login function

How to implement AJAX non-refresh login function

Jan 24, 2017 pm 01:30 PM

When you click the login button, a login window will pop up. After entering the correct username and password and clicking login, the login window will close and the status will be changed to the current username. This article mainly introduces how AJAX implements the refresh-free login function. Friends who need it can refer to it. Next

When you click the login button, a login window will pop up. After entering the correct username and password and clicking login, the login window will close and the status will be changed to the current username.

Step 1:

First of all, the pop-up window uses the controls in jquery-ui. The first step is to learn how to use it.

Open the development-bundle->demos under the decompressed jquery-UI and find index.html , select the model dialog under dialog, right-click to view the source code, observe how to use the control, and find a key code: $("#dialog-modal").dialog({height: 140,modal: true}); This is used If displayed, open the source code in the model message and find the key code for closing: $(this).dialog('close'); with these two lines of code, you can control the display and closing of the window, and you can proceed to the next step. Use You need to copy the css folder and js folder of the jquery-ui development package to the project.

Step 2:

Post the code of the general handler for handling AJAX requests here. , although when I actually write, I use it before writing, but it is impossible to list it in detail step by step here. In order to facilitate understanding, I will post the general handler code first:

1.IsLogin.ashx, use To determine whether the user is logged in, the user name will be returned when logging in. Note here that to use session in the general processing program, using System.Web.SessionState must be introduced and the IRequiresSessionState interface must be implemented

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace AJAX无刷新登录.AJAX
{
 /// <summary>
 /// IsLogin 的摘要说明
 /// </summary>
 public class IsLogin : IHttpHandler,IRequiresSessionState
 {
  public void ProcessRequest(HttpContext context)
  {
   context.Response.ContentType = "text/plain";
   if (context.Session["userName"] != null)
   {
    string userName = context.Session["userName"].ToString();
    context.Response.Write("yes|"+userName);
   }
   else
   {
    context.Response.Write("no");
   }
  }
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }
}
Copy after login

2.CheckLogin.ashx, Used to detect whether the user name and password entered by the user match. If it is correct, it will return yes, if it is wrong, it will return no. For simplicity, the database is not connected here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace AJAX无刷新登录.AJAX
{
 /// <summary>
 /// CheckLogin 的摘要说明
 /// </summary>
 public class CheckLogin : IHttpHandler,IRequiresSessionState
 {
  public void ProcessRequest(HttpContext context)
  {
   context.Response.ContentType = "text/plain";
   string userName = context.Request["userName"];
   string password=context.Request["password"];
   if (userName=="admin"&&password=="admin")
   {
    context.Session["userName"] = "admin";
    context.Response.Write("ok");
   }
   else
   {
    context.Response.Write("no");
   }
  }
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }
}
Copy after login

3.LoginOut.ashx, used to control user logout, set the session to Empty.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace AJAX无刷新登录.AJAX
{
 /// <summary>
 /// LoginOut 的摘要说明
 /// </summary>
 public class LoginOut : IHttpHandler,IRequiresSessionState
 {
  public void ProcessRequest(HttpContext context)
  {
   context.Response.ContentType = "text/plain";
   context.Session["userName"] = null;
  }
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }
}
Copy after login

The general processing program is over. The code of the main interface is posted below:

<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title></title>
 <link href="JQueryUI/css/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" />
 <script src="JQueryUI/jquery-1.4.2.min.js"></script>
 <script src="JQueryUI/jquery-ui-1.8.2.custom.min.js"></script>
 <script type="text/javascript">
  //判断是否登录,登录则显示登录名,隐藏登录按钮,显示注销按钮
  //否则相反
  var isLogin = function () {
   $.post("/AJAX/IsLogin.ashx", function (data) {
    var strs = data.split(&#39;|&#39;);
    if (strs[0] == "yes") {
     $("#divShowLogin").hide();
     $("#divShowLoginOut").show();
     $("#spanName").text(strs[1]);
    } else {
     $("#divShowLogin").show();
     $("#divShowLoginOut").hide();
     $("#spanState").text("未登录");
    }
   });
  }
 
  $(function () {
   isLogin();
   //点击登录弹出登录窗口
   $("#btnShowLogin").click(function () {
    //模态窗口,设定长宽
    $("#divLogin").dialog({
     height: 160,
     width: 300,
     modal: true
    });
   });
 
   //点击取消则关闭弹出框
   $("#btnCancel").click(function () {
    $("#divLogin").dialog(&#39;close&#39;);
   });
 
   //点击登录发送post请求在一般处理程序CheckLogin.ashx中验证登录,
   //根据回调函数结果判断是否登录成功
   $("#btnLogin").click(function () {
    var userName = $("#txtUserName").val();
    var password = $("#txtPwd").val();
    $.post("/AJAX/CheckLogin.ashx", { "userName": userName, "password": password }, function (data) {
     if (data == "ok") {
      $("#divLogin").dialog(&#39;close&#39;);
      isLogin();
     }
     else {
      alert("用户名或密码错误");
     }
    });
   });
 
   //点击注销发送post请求,在一般处理程序中设置session为null,并调用isLogin函数刷新状态
   $("#btnExit").click(function () {
    $.post("/AJAX/LoginOut.ashx", function () {
     isLogin();
    });
 
   });
 
  });
 </script>
</head>
<body>
 <form id="form1" runat="server">
  <div id="divShowLogin" style="display: none">
   <span id="spanState"></span>
   <input type="button" value="登录" id="btnShowLogin" />
  </div>
  <div id="divShowLoginOut" style="display: none">
   <span id="spanName"></span>
   <input type="button" value="注销" id="btnExit" />
  </div>
  <div id="divLogin" title="登录窗口" style="display: none">
   <table style="text-align: left" id="tbLoin">
    <tr>
     <td>用户名:</td>
     <td>
      <input type="text" id="txtUserName" /></td>
    </tr>
    <tr>
     <td>密码:</td>
     <td>
      <input type="password" id="txtPwd" /></td>
    </tr>
    <tr>
     <td>
      <input type="button" value="登录" id="btnLogin" /></td>
     <td style="text-align: left">
      <input type="button" value="取消" id="btnCancel" /></td>
    </tr>
   </table>
  </div>
 </form>
</body>
</html>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

See all articles