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; } } } }
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; } } } }
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; } } } }
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('|'); 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('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") { $("#divLogin").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"> <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>

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
