Today, I learned three ways to access the back-end database through Ajax. The front-end is javascript + html, and the back-end is a handler (general processing program). I will not describe much about the above principles, after the user name is entered, the user name is corrected. In this example, the asynchronous request method is used to set the third parameter of open to true. If synchronous request is used, you can change it to false without the onreadystatechange method.
1. Process strings or html (GET)
Front-end:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> User Registration </title>
<Script type = "text/javascript">
// Create an XMLHttpRequest object
Function createXMLHttpRequest (){
Var xmlhttp = null;
Try {
Xmlhttp = new XMLHttpRequest ();
} Catch (e ){
Var MSXML = ['msxml2. XMLHTTP.6.0 ', 'msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP '];
For (var n = 0; n <MSXML. length; n ++ ){
Try {
Xmlhttp = new ActiveXObject (MSXML [n]);
Break;
} Catch (e ){}
}
}
Return xmlhttp;
}
// GET request using Ajax steps
Function checkUserByAjaxByGet (){
Var name = document. getElementById ("name"). value;
// Step 1: Get An XMLHttpRequest object
// Var xhr = new XMLHttpRequest ();
// If it is IE, ActiveX components must be used.
// Var xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP ");
Var xhr = createXMLHttpRequest ();
// Step 2: create a connection request. "false" indicates synchronous execution, and the server continues execution only after execution is complete. "true" indicates asynchronous execution, without waiting for the server to continue execution; the common method is true (asynchronous)
Xhr. open ("GET", "checkUserPostOrGetHandler. ashx? Name = "+ name, true );
// Set a listening function for reandyonchange events
Xhr. onreadystatechange = function (){
// Document. getElementById ("statusMsg"). innerHTML + = "readyState:" + xhr. readyState + ", status" + xhr. status + "<br/> ";
// ReadyState: 0, indicating that the open method is not initialized, and the open method is not called. 1. indicates that the method is being loaded. The open method has been called, but the send method has not been called. 2. It indicates that the load has been completed, the send method has been called, and the request has started. 3. It indicates that the interaction is in progress, the server is sending a response. 4. The response is completed.
// Status: 404, page not found (not found); 403, access prohibited (forbidden); 500, internal server error (internal service error ); 200 normal together (OK); 304, not modified (not modified) (the server returns the 304 status, indicating that the source file has not been modified
If (xhr. readyState = 4 ){
If (xhr. status = 200 | xhr. status = 304 ){
Document. getElementById ("msg"). innerHTML = xhr. responseText;
}
}
}
// Step 3: initiate a request
Xhr. send (null );
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<P>
User name:
<Input type = "text" id = "name" runat = "server" onchange = "checkUserByAjaxByGet ()"/>
</P>
<Div id = "msg"> </div>
<P>
Password:
<Input type = "password" id = "pwd"/>
</P>
</Form>
<Div id = "statusMsg"> </div>
</Body>
</Html>
Background:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Namespace ExtjsApplication. Demo3
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
Public class checkUserPostOrGetHandler: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String name = context. Request. Params ["name"];
String msg = "congratulations, this user is available ";
If ("admin". Equals (name )){
// You should actually call the background database or business logic
Msg = "sorry, the user already exists ";
}
Context. Response. Write (msg );
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}
2. Process strings or html (POST)
Front-end:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> User Registration </title>
<Script type = "text/javascript">
// Create an XMLHttpRequest object
Function createXMLHttpRequest (){
Var xmlhttp = null;
Try {
Xmlhttp = new XMLHttpRequest ();
} Catch (e ){
Var MSXML = ['msxml2. XMLHTTP.6.0 ', 'msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP '];
For (var n = 0; n <MSXML. length; n ++ ){
Try {
Xmlhttp = new ActiveXObject (MSXML [n]);
Break;
} Catch (e ){}
}
}
Return xmlhttp;
}
// Use the Ajax step and the POST Request Method
Function checkUserByAjaxByPost (){
Var name = document. getElementById ("name"). value;
// Step 1: Create an XHR object
Var xhr = createXMLHttpRequest ();
// Step 2: create a connection request. "false" indicates synchronous execution, and the server continues execution only after execution is complete. "true" indicates asynchronous execution, without waiting for the server to continue execution; the common method is true (asynchronous)
Xhr. open ("POST", "checkUserPostOrGetHandler. ashx", true );
// Step 3: Set a listening function for reandyonchange events to process the returned results.
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 ){
If (xhr. status = 200 | xhr. status = 304 ){
Var ret = xhr. responseText;
Document. getElementById ("msg"). innerHTML = xhr. responseText;
If (ret = "sorry, the user already exists "){
Document. getElementById ("name"). focus ();
}
}
}
}
// Set the request header. If it is a post request, it must be set to send a file in the form, which is equivalent to enctype = "application/x-www-form-urlencoded" in the form"
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
// Step 4: initiate a request
Xhr. send ("name =" + name + "& password = pppp ");
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<P>
User name:
<Input type = "text" id = "name" runat = "server" onchange = "checkUserByAjaxByPost ()"/>
</P>
<Div id = "msg"> </div>
<P>
Password:
<Input type = "password" id = "pwd"/>
</P>
</Form>
<Div id = "statusMsg"> </div>
</Body>
</Html>
Background:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Namespace ExtjsApplication. Demo3
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
Public class checkUserPostOrGetHandler: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String name = context. Request. Params ["name"];
String msg = "congratulations, this user is available ";
If ("admin". Equals (name )){
// You should actually call the background database or business logic
Msg = "sorry, the user already exists ";
}
Context. Response. Write (msg );
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}
Iii. XML Processing
Front-end:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> User Registration </title>
<Script type = "text/javascript">
// Create an XMLHttpRequest object
Function createXMLHttpRequest (){
Var xmlhttp = null;
Try {
Xmlhttp = new XMLHttpRequest ();
} Catch (e ){
Var MSXML = ['msxml2. XMLHTTP.6.0 ', 'msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP '];
For (var n = 0; n <MSXML. length; n ++ ){
Try {
Xmlhttp = new ActiveXObject (MSXML [n]);
Break;
} Catch (e ){}
}
}
Return xmlhttp;
}
// Use Ajax to access the server in XML format
Function checkUserByAjaxByXML (){
Var name = document. getElementById ("name"). value;
// Step 1: Create an XHR object
Var xhr = createXMLHttpRequest ();
// Step 2: create a connection request. "false" indicates synchronous execution, and the server continues execution only after execution is complete. "true" indicates asynchronous execution, without waiting for the server to continue execution; the common method is true (asynchronous)
Xhr. open ("POST", "checkUserXMLHandler. ashx", true );
// Step 3: Set a listening function for reandyonchange events to process the returned results.
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 ){
If (xhr. status = 200 | xhr. status = 304 ){
Var ret = xhr. responseXML;
Var root = ret.doc umentElement;
Var codeNode = root. getElementsByTagName ("code") [0];
Var MsgNode = root. getElementsByTagName ("msg") [0];
// Alert (root. getElementsByTagName ("code") [0]. nodeName );
// Alert (root. firstChild. firstChild. nodeValue );
// Alert (root. childNodes [0]. childNodes [0]. nodeValue );
// Alert(ret.doc umentElement. nodeName );
// Alert (ret );
// Document. getElementById ("msg"). innerHTML = xhr. responseXML;
// If (ret = "sorry, the user already exists "){
// Document. getElementById ("name"). focus ();
//}
Document. getElementById ("msg"). innerHTML = MsgNode. firstChild. nodeValue;
If (codeNode. firstChild. nodeValue = "1 "){
Document. getElementById ("name"). focus ();
}
}
}
}
// Set the request header. If it is a post request, it must be set to send a file in the form, which is equivalent to enctype = "application/x-www-form-urlencoded" in the form"
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
// Step 4: initiate a request
Xhr. send ("name =" + name + "& password = pppp ");
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<P>
User name:
<Input type = "text" id = "name" runat = "server" onchange = "checkUserByAjaxByXML ()"/>
</P>
<Div id = "msg"> </div>
<P>
Password:
<Input type = "password" id = "pwd"/>
</P>
</Form>
<Div id = "statusMsg"> </div>
</Body>
</Html>
Background:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Namespace ExtjsApplication. Demo3
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
Public class checkuserpostorgethandler: ihttphandler
{
Public void processrequest (httpcontext context)
{
Context. response. contenttype = "text/XML ";
String name = context. Request. Params ["name"];
String MSG = "congratulations, this user is available ";
Int code = 0;
If ("admin". Equals (name ))
{
// You should actually call the background database or business logic
MSG = "sorry, the user already exists ";
Code = 1;
}
// Context. response. Write (MSG );
Context. response. write ("<result> <code>" + code + "</code> <MSG>" + MSG + "</MSG> </result> ");
}
Public bool isreusable
{
Get
{
Return false;
}
}
}
}
4. Process JSON
Front-end:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> User Registration </title>
<Script type = "text/javascript">
// Create an XMLHttpRequest object
Function createXMLHttpRequest (){
Var xmlhttp = null;
Try {
Xmlhttp = new XMLHttpRequest ();
} Catch (e ){
Var MSXML = ['msxml2. XMLHTTP.6.0 ', 'msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0 ', 'msxml2. XMLHTTP.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP '];
For (var n = 0; n <MSXML. length; n ++ ){
Try {
Xmlhttp = new ActiveXObject (MSXML [n]);
Break;
} Catch (e ){}
}
}
Return xmlhttp;
}
// Use Ajax to access the server in JSON format
Function checkUserByAjaxByJson (){
Var name = document. getElementById ("name"). value;
// Step 1: Create an XHR object
Var xhr = createXMLHttpRequest ();
// Step 2: create a connection request. "false" indicates synchronous execution, and the server continues execution only after execution is complete. "true" indicates asynchronous execution, without waiting for the server to continue execution; the common method is true (asynchronous)
Xhr. open ("POST", "checkUserJsonHandler. ashx", true );
// Step 3: Set a listening function for reandyonchange events to process the returned results.
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 ){
If (xhr. status = 200 | xhr. status = 304 ){
Var ret = eval ("(" + xhr. responseText + ")");
// Alert (ret );
Document. getElementById ("msg"). innerHTML = ret. msg;
If (ret. code = "1 "){
Document. getElementById ("name"). focus ();
}
}
}
}
// Set the request header. If it is a post request, it must be set to send a file in the form, which is equivalent to enctype = "application/x-www-form-urlencoded" in the form"
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
// Step 4: initiate a request
Xhr. send ("name =" + name + "& password = pppp ");
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<P>
User name:
<Input type = "text" id = "name" runat = "server" onchange = "checkUserByAjaxByJson ()"/>
</P>
<Div id = "msg"> </div>
<P>
Password:
<Input type = "password" id = "pwd"/>
</P>
</Form>
<Div id = "statusMsg"> </div>
</Body>
</Html>
Background:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Namespace ExtjsApplication. Demo3
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
Public class checkUserPostOrGetHandler: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/json ";
String name = context. Request. Params ["name"];
String msg = "congratulations, this user is available ";
Int code = 0;
If ("admin". Equals (name ))
{
// You should actually call the background database or business logic
Msg = "sorry, the user already exists ";
Code = 1;
}
// Context. Response. Write (msg );
// Context. response. write ("{code: '" + code + "', msg: '" + msg + "', obj: {name: 'obj '}}");
Context. Response. Write ("{code: '" + code + "', msg: '" + msg + "'}");
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}