search
HomeWeb Front-endJS TutorialHow does JavaScript control Session operations? Method introduction

This article will introduce to you how to control Session operations using JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How does JavaScript control Session operations? Method introduction

Seeing this question, some people may raise questions. JavaScript represents the client, while Session represents the server (I don’t know if everyone can understand this).

Let me talk about the requirements first. When I am doing permission management, I need to change the module code in the Session accordingly when I click on a certain module. What implements this operation is an a tag. Of course I don’t know. Is it possible for a link button to jump to the page and modify the session at the same time? Personally, I think it is possible. If someone has made a demo, you can leave a message to explain.

a tag implements page jump. Its onclick event also executes the js method in this page. Now we are back to the problem described in the title - write a JavaScript method to modify the Session. .

In fact, this example is not difficult, but it has extraordinary personal significance to me. This example relieved a large part of my fear of AJAX.
First, write a general handler (that is, server-side code)

It should be noted that if you want to modify the Session, you need to introduce an additional namespace and implement an interface (you only need to implement it, otherwise No need to do anything)

The code is as follows:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.SessionState; 
namespace TGB.CJX 
{ 
/// <summary> 
/// 修改Session 
/// </summary> 
public class ModifySession : IHttpHandler,IRequiresSessionState 
{ 
public void ProcessRequest(HttpContext context) 
{ 
context.Response.ContentType = "text/plain"; 
context.Session["modelID"]=context.Request.QueryString["session"].ToString(); 
//context.Session["modelID"] = "1"; 
//context.Response.Write(context.Session["modelID"]); 
} 
public bool IsReusable 
{ 
get 
{ 
return false; 
} 
} 
} 
}

Did you find that the function implemented above is very simple?

The following is the client code

The code is as follows:

var xmlhttp; 
var session; 
function submit(obj) { 
//session = obj.id.substr(1, 1); 
session = obj.id.replace("model",""); 
//IE7,IE8,FF,MOZILLA,SAFARI 
if (window.XMLHttpRequest) { 
//alert("IE7,IE8,FF,MOZILLA,SAFARI"); 
xmlhttp = new XMLHttpRequest(); 
if (xmlhttp.overrideMinmeType) { 
xmlhttp.overrideMinmeType("text/xml"); 
} 
} else if (window.ActiveXObject) { 
//alert("IE5,IE6"); 
var activeName = ["MSXML2.XMLHTTP", "Miscrosoft.XMLHTTP"]; 
for (var i = 0; i < activeName.length; i++) { 
try { 
xmlhttp = new ActiveXObject(activeName[i]); 
break; 
} catch (e) { 
return; 
} 
} 
} 
if (xmlhttp == undefined || xmlhttp == null) { 
alert("当前浏览器不支持创建XMLHTTPREQUEST对象,请更换浏览器"); 
return; 
} 
xmlhttp.onreadystatechange = callback; 
xmlhttp.open("GET", "ModifySession.ashx?session=" + session, true); 
xmlhttp.send(null); 
} 
function callback() { 
//判断和服务器的交互是否完成,还要判断服务器端是否返回了数据 
if (xmlhttp.readyState == 4) { 
//表示和服务器端的交互完成 
if (xmlhttp.status == 200) { 
//alert("正确返回了数据"); 
return; 
} 
} 
}

In the callback function, I only wrote a statement to test the normal return of data, It was later commented out.
When binding events to the a tag, I initially used the method of splicing strings, which is to find the module ID and module name from the database, and then splice the statements through the following statement:

StringBuilder sbModel = new StringBuilder(); 
//将可以访问的模块进行菜单拼接 
for (int i = 0; i < dtModel.Rows.Count; i++) 
{ 
sbModel.Append("<li><a id=&#39;model" + dtModel.Rows[0]["mdlID"].ToString() + "&#39; href=&#39;SpaceWeb.aspx&#39; target=&#39;_parent&#39; runat=&#39;server&#39; onclick=&#39;submit(this)&#39;>" + dtModel.Rows[i]["mdlName"].ToString() + "</a></li>"); 
}

But writing like this is easy to make mistakes. Although I wrote test statements before copying in, and then wrote the variables to the writing position, the statements written in this way are difficult to debug.

In the process of communicating with others, I talked about the Repeater control, and suddenly realized that the process I repeated was what the Repeater control did? The control does it for us, why do we need to write such error-prone code ourselves?

<asp:Repeater runat="server" id="rptModel"> 
<ItemTemplate> 
<li><a id=&#39;model&#39;+&#39;<%#Eval("mdlID")%>&#39; href="SpaceWeb.aspx" target="_parent" runat="server" onclick="submit(this)"><%#Eval("mdlName" %></a></li> 
</ItemTemplate> 
</asp:Repeater>

If you write it like this, it will feel much clearer, because I used to splice strings before and implemented it. Using Repeater is just an idea. I don’t know if there will be any problems when splicing ids. , if there is any problem, please correct me.

So far, I have finished writing my first article about AJAX. The understanding of AJAX is just the beginning. It does not involve data interaction, so the explanation of some knowledge is still a bit pale. With the deepening of learning, the use of AJAX will not just stop at controls such as updatepanel and timer. For some examples that are not too difficult, it is better to do it yourself.

Regarding this example, you can ask why it’s so troublesome when you can actually use a LinkButton to achieve it. But I want to say that I didn’t think that a LinkButton could solve the problem at first. I just complicated the problem myself. Yes, this involves a page jump. In fact, it can be solved with LinkButton, but learning is a process. It is a pleasure to use a little confusion I made to promote my understanding of AJAX~~

The understanding of AJAX is still being progressed step by step. If there are any mistakes, please leave comments and comments

For more programming-related knowledge, please visit: Introduction to Programming! !

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools