Instance requirements:
The process of using AJAX technology to implement a page that does not refresh and to verify that a user name has been registered.
Requirements:
Add a text box label to the page to enter a user name and add a button to submit the user data. The results of the validation are printed directly on the page.
The procedure is as follows:
1) Open Visual Studio 2005 to build a Web site
2) Add a control and a control to the HTML bar of the VS2005 Toolbox.
3) Add <script type = "Text/javascript" ></script> tag in <Head></Head> for the Ajax engine to be written, And a XMLHttpRequest object is basically defined, but not initialized. As shown in the following code.
var xmlhttp;
function Validation ()
{
Instantiating a XMLHttpRequest Object
XMLHTTP =new ActiveXObject ("Microsoft.XMLHTTP");
Find a text box named "Text1"
var name=document. getElementById ("Text1");
Use the Open method to specify a URL
The query string "name" transfers the data in the text box to the target page
Xmlhttp.open ("Post", "ajaxdemo_1.aspx?name=" +name.value);
Sets the name of the function used to process the response when the server response is returned
XMLHTTP. Onreadystatechange=onmessageback;
Communicated request
XMLHTTP. Send (NULL);
}
4) Add the contents of the Onmessageback () function. The code is as follows:
function Onmessageback ()
{
Determine whether the request status and HTTP status satisfy the condition
if (XMLHTTP. readystate==4&&xmlhttp. status==200)
{
Print the returned text to the page
Document. write (XMLHTTP. responsetext);
}
}
5) Add the event code for Button1 below to change its label to
<input id= "Button1" type= "button" value= "button" onclick= "Validation ()"/>
6) The Ajax engine in the page has been written. In the code, you can see that the user name is passed through a query string called "name", which is passed to the server and requires background processing, so the Page_ in "AjaxDemo_1.aspx.cs" The Load method adds some ADO code. The database here uses the "Northwind" sample database. The code is shown below.
protected void Page_Load (object sender, EventArgs e)
{
String name = request.querystring["Name"];
if (name! = NULL)
{
SqlConnection con = new SqlConnection ("");
SqlCommand com = new SqlCommand ();
Com.commandtext = "";
Com. Parameters.Add ("@CustomerID", sqldbtype.nchar,5). Value =name;
Con. Open ();
int count = (int) com. ExecuteScalar ();
Con. Close ();
if (count = = 0)
{
Response.Write ("<script>alert (' the user can use! '); </script> ");
}
Else
{
Response.Write ("<script>alert (' the user is already occupied, please use a different user name!") ');</script> ");
}
}
}
It is important to note that when the server responds to the client using the Response.Write () method, the client's AJAX engine intercepts the response stream and processes it in our pre-defined "Onmessageback ()" method.