Home Web Front-end JS Tutorial Javascript XMLHttpRequest asp.net reads database data without refreshing_javascript skills

Javascript XMLHttpRequest asp.net reads database data without refreshing_javascript skills

May 16, 2016 pm 06:48 PM
asp.net javascript No refresh

复制代码 代码如下:

/**////
/// 生成带CDATA的节点
///

/// XmlDocument
/// 元素名称
/// CDATA值
/// XmlElement
public static XmlElement CreateXmlNodeCDATA(XmlDocument xDocument, string elementName, string cdataValue)
{
try
{
XmlElement xElement = xDocument.CreateElement(elementName);
XmlCDataSection cdata = xDocument.CreateCDataSection(cdataValue);
xElement.AppendChild(cdata);
return xElement;//返回
}
catch (Exception ex)
{
throw ex;
}
}
Helper#region Helper
/**////
/// 向页面输出xml内容
///

/// xml内容
private void ResponseXML(XmlDocument xmlNode)
{
System.Web.HttpContext.Current.Response.Expires = 0;
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Cache.SetNoStore();
System.Web.HttpContext.Current.Response.ContentType = "text/xml";
System.Web.HttpContext.Current.Response.Write(xmlNode.OuterXml);
System.Web.HttpContext.Current.Response.End();
}
/**////
/// 创建Ajax返回信息
///

///
private void CreateResponse(string result)
{
XmlDocument xDocument = new XmlDocument();
XmlDeclaration declare = xDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlElement root = xDocument.CreateElement("root");
XmlElement eleResponse = CreateXmlNodeCDATA(xDocument, "response", result);
root.AppendChild(eleResponse);
xDocument.AppendChild(declare);
xDocument.AppendChild(root);
ResponseXML(xDocument);
System.Web.HttpContext.Current.Response.End();
}
/****////
/// 向页面输出xml内容
///

/// xml内容
private void ResponseXML(XmlDocument xmlNode)
{
System.Web.HttpContext.Current.Response.Expires = 0;
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Cache.SetNoStore();
System.Web.HttpContext.Current.Response.ContentType = "text/xml";
System.Web.HttpContext.Current.Response.Write(xmlNode.OuterXml);
System.Web.HttpContext.Current.Response.End();
}


There are many topics about Ajax on the Internet, but many of them are implemented using control open source frameworks. In particular, vs2008 integrates many ajax controls, which tightly encapsulates the ajax execution process. I have also used these frameworks and controls, and they feel great. But recently, on a whim, I wanted to see how ajax is executed, so I wanted to implement it myself, which just happened to exercise my js skills. Without further ado, as the title states, let’s take a look at the execution process.
1. This implementation uses a total of two pages: AjaxTest6.aspx and Ajax.aspx
Among them, AjaxTest6.aspx is the page that initiates the request, and Ajax.aspx gets the request of AjaxTest6.aspx and processes it. .
Processing process: (1) AjaxTest6.aspx initiates an http request ---> (2) Ajax.aspx obtains the parameters in the url, performs query operations in the database based on these parameters and returns the results (data set) -- ->(3) Process the returned data set as XML and output it through response. Note that the format of the output data now is xml --- (4) AjaxTest6.aspx obtains the output xml data of Ajax.aspx and displays it
2. The js code in AjaxTest6.aspx
Copy code The code is as follows:

< script language="javascript" type="text/javascript">
< script language="javascript" type="text/javascript">

Description: The first function createXMLHttpRequest is used to create an XMLHttpRequest object. For detailed descriptions of this object, please refer to related articles. Now you just need to understand that this object is used when we use http requests to send data and use xml to transfer data. , after the declaration, we can use it below
The second function is used to send http requests. Generally, the URL has parameters, through xmlhttp.open("GET","Tools/Ajax.aspx? cateid=" vr1,true); We can see from this sentence that a request with parameters is sent to Ajax.aspx. Ajax.aspx captures this parameter and then executes a query in the database based on this parameter. The specific processing process will be described in detail below. .
In this function we also need to pay attention to the sentence view plaincopy to clipboardprint?
xmlhttp.onreadystatechange=handleStateChange;//This method is called when the request status changes
xmlhttp.onreadystatechange=handleStateChange;//In This method is called when the request status changes
Because the xmlhttp object is divided into several stages during execution, each stage corresponds to a different status value: 0 means initialization, 1 means loading, 2 means loaded. , 3 means interactive, 4 means completed
So the above code means that the handleStateChange method will be executed as long as the state of the xmlhttp object changes. Its specific functions are as follows:
This method first finds the div that displays the data. tag (ret), and then determine the execution status of xmlhttp. When the status value becomes 4 and xmlhttp.status==200 (status is the server's http status code 200 corresponding to OK and 404 corresponding to Not Found. If you are not very familiar with the xmlhttprequest object, It is recommended that you familiarize yourself with it first)
Obviously when xmlhttp.onready==4 and xmlhttp.stauts==200 means that all the data has been read out on the server side. At this time, the data is placed in an xml file. This xml file We generate it on the server side.
Everything is ready for program execution. Now we just need to read the xml file from the browser. At this time, you should pay attention to the last function GetText() we will talk about below.
This function first tells the browser that we want to read an xml object (of course you can also set it to a string format, for example: var xmlDoc =xmlhttp.responseText); The reason why we set the data set to xml format is because it can be parsed into a DOM object at this time, so that we can process it very flexibly below.
Now that we have finished talking about the client code, let’s talk about the server-side execution process. This process is completed in the post-code of Ajax.aspx
1. First, we get the url in the Page_Load event parameter, which is sent from AjaxTest6.aspx. Then execute the query based on this parameter. I will not explain the specific code in detail. You can understand it at a glance. The code is as follows:
Copy code The code is as follows:

private static readonly string sql = "server=xxx;database=xxx;uid=sa;pwd=xxx";
protected void Page_Load(object sender, EventArgs e)
{
string id=Request.QueryString["cateid"];
System.Threading.Thread.Sleep(2000);
GetTitle(Convert.ToInt32(id));
}

private DataTable GetLogs(int cateid)
{
using (SqlConnection con = new SqlConnection(sql))
{
con.Open();
string select = "SELECT Id,CateId,LogTitle FROM Logs WHERE CateId = " cateid;
SqlDataAdapter sda = new SqlDataAdapter(select, con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
return dt;
}
}

public void GetTitle(int id)
{
DataTable dt = GetLogs(id) ;
StringBuilder sb = new StringBuilder();
if (dt != null && dt.Rows.Count>0)
{
for (int i = 0; i < dt.Rows .Count;i )
{
sb.AppendLine(dt.Rows[i][2].ToString());
}
CreateResponse(sb.ToString());
}
}
private static readonly string sql = "server=xxx;database=xxx;uid=sa;pwd=xxx";
2 protected void Page_Load(object sender, EventArgs e)
3 {
4 string id=Request.QueryString["cateid"];
5 System.Threading.Thread.Sleep(2000);
6 GetTitle(Convert.ToInt32(id));
7 }
8
9 private DataTable GetLogs(int cateid)
{
using (SqlConnection con = new SqlConnection(sql))
{
con.Open();
string select = "SELECT Id,CateId,LogTitle FROM Logs WHERE CateId = " cateid;
SqlDataAdapter sda = new SqlDataAdapter(select, con);
DataTable dt = new DataTable();
sda.Fill( dt);
con.Close();
return dt;
}
}

public void GetTitle(int id)
{
DataTable dt = GetLogs (id);
StringBuilder sb = new StringBuilder();
if (dt != null && dt.Rows.Count>0)
{
for (int i = 0; i < dt.Rows.Count;i )
{
sb.AppendLine(dt.Rows[i][2].ToString());
}
CreateResponse(sb.ToString());
}
}

Note: As can be seen from GetTitle (int id), I converted the data read from the library into a string and handed it to the CreateResponse method (it may not be appropriate here because it may not be safe when the amount of data is large) , the following is about the operation of converting data into xml files
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 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 to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles