Home Web Front-end JS Tutorial AJAX implementation without refreshing login

AJAX implementation without refreshing login

Apr 02, 2018 pm 04:31 PM
ajax accomplish Log in

This time I will bring you AJAX to implement non-refresh login, and what are the precautions for AJAX to implement non-refresh login. The following is a practical case, let's take a look.

I recently learned how to achieve non-refresh login. The general effect is as follows (the interface is ugly, please ignore it...):

Click to log in When the button is pressed, a login window pops up. After entering the correct username and password, click Login and the login window closes and the status changes to the current username.

Step 1:

First The pop-up window uses 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 for display. 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 display of the window. Close and you can proceed to the next step. When using it, you need to copy the css folder and js folder of the jquery-ui development package to the project.

Second step:

Here I will first post the code for the general handler that handles AJAX requests. Although I use it before writing it, it is impossible to list it in detail here step by step. In order to facilitate understanding, I will first post the code for the general handler. Out:

1.IsLogin.ashx, used to determine whether the user is logged in, and returns the user name when logged in. Note here that to use session in a general handler, using System.Web.SessionState must be introduced and implemented IRequiresSessionState interface

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 the sake of simplicity, there is no

Connect to the database.

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 is used to control user logout and set the session to be 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:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="AJAX无刷新登录.Login" %>
Copy after login
<!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('|');
    if (strs[0] == "yes") {
     $("#pShowLogin").hide();
     $("#pShowLoginOut").show();
     $("#spanName").text(strs[1]);
    } else {
     $("#pShowLogin").show();
     $("#pShowLoginOut").hide();
     $("#spanState").text("未登录");
    }
   });
  }
  $(function () {
   isLogin();
   //点击登录弹出登录窗口
   $("#btnShowLogin").click(function () {
    //模态窗口,设定长宽
    $("#pLogin").dialog({
     height: 160,
     width: 300,
     modal: true
    });
   });
   //点击取消则关闭弹出框
   $("#btnCancel").click(function () {
    $("#pLogin").dialog('close');
   });
   //点击登录发送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") {
      $("#pLogin").dialog('close');
      isLogin();
     }
     else {
      alert("用户名或密码错误");
     }
    });
   });
   //点击注销发送post请求,在一般处理程序中设置session为null,并调用isLogin函数刷新状态
   $("#btnExit").click(function () {
    $.post("/AJAX/LoginOut.ashx", function () {
     isLogin();
    });
   });
  });
 </script>
</head>
<body>
 <form id="form1" runat="server">
  <p id="pShowLogin" style="display: none">
   <span id="spanState"></span>
   <input type="button" value="登录" id="btnShowLogin" />
  </p>
  <p id="pShowLoginOut" style="display: none">
   <span id="spanName"></span>
   <input type="button" value="注销" id="btnExit" />
  </p>
  <p id="pLogin" 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>
  </p>
 </form>
</body>
</html>
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How ajax implements the paging query function of bootstrap modal box

Cookie is lost during Ajax cross-domain access How to solve

How to use Ajax and $.ajax

The above is the detailed content of AJAX implementation without refreshing login. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the &quot;Login&quot; button. (2) Select &quot;Retrieve Password&quot;. (3) Enter the mobile phone number you used when registering your account

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? Mar 23, 2024 pm 05:31 PM

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the &quot;Login&quot; button and select &quot;Account and Password Login&quot;; 3. Click the &quot;Forgot your password?&quot; button; 4. Enter your account number. Click &quot;Next&quot;; 5. The system will send a verification code to your mobile phone, enter the verification code and click &quot;OK&quot;; 6. Set a new password and confirm. You can also use a third-party account (such as

How to solve the common problem of Laravel login time invalidation How to solve the common problem of Laravel login time invalidation Mar 06, 2024 pm 09:24 PM

How to solve the common problem of Laravel login time expiration When using Laravel to develop web applications, login authentication is a very important function. However, sometimes if a user does not operate for a long time after logging in, the page may automatically log out or the authentication may fail. This problem is relatively common. The following will introduce how to solve this problem by setting the session time and provide specific code examples. 1. Set the session expiration time in Laravel, by default sessi

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

See all articles