Easily master the XMLHttpRequest object------"This is the. NET version"

Source: Internet
Author: User

Easily master XMLHttpRequest objects what is XMLHTTP?

The most common definition is: XMLHTTP is a set of APIs that can be routed through the HTTP protocol or received from XML and other data in scripting languages such as JavaScript, VbScript, and JScript. The biggest use of XMLHTTP is to update parts of the Web page without having to refresh the entire page.

Explanation from MSDN: XMLHTTP provides the protocol for the client to communicate with the HTTP server. The client can pass the XMLHTTP object (MSXML2. xmlhttp.3.0) sends a request to the HTTP server and uses the Microsoft XML Document Object Model Microsoft®xml Document object (DOM) to process the response. Now the absolute majority of browsers have added support for XMLHTTP, IE uses activexobject way to create XMLHTTP objects, other browsers such as: Firefox, Opera waits to create XMLHTTP objects through Window.xmlhttprequest.

properties of the XMLHTTP object:

Methods for XMLHTTP objects:


How do I send a simple request?
The simplest request is to not send any information to the server in the form of query parameters or submissions. Basic steps for sending requests using the XMLHttpRequest object:
To get a reference to the XMLHttpRequest object instance, you can create a new instance of the XMLHttpRequest.
Tells the XMLHttpRequest object that the function returns a change to the state of the XMLHttpRequest object. For this purpose, the object's
The onReadyStateChange property is set to a pointer to JavaScript.
Specifies the request properties. The open () method of the XMLHttpRequest object specifies the request that will be sent.
Send the request to the server. The Send () method of the XMLHttpRequest object sends the request to the target resource.

XMLHttpRequest Example Analysis
I think we all know that if we want to use a non-object, what do we have to do first? You must first create an object. For example, C # and Java use new to instantiate an object. So I'm going to use the XMLHTTP object now. Should we create a XMLHTTP object? There is no doubt about it! So let's take a look at how the client creates a XMLHTTP object and uses this object to send an HTTP request to the server and then process the response information returned by the servers.

1. Create an XMLHTTP object (where I do an instance of the addition operation with no flush)

1var xmlHttp;
2function Createxmlhttprequest ()
3{
4 if (window. ActiveXObject)
5 {
6 xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
7}
8 Else if (window. XMLHttpRequest)
9 {
Ten xmlHttp = new XMLHttpRequest ();
11}
--}

2. Define the method of sending the request

1//Treatment Method
2function Addnumber ()
3{
4 Createxmlhttprequest ();
5 var url= "addhandler.ashx?num1=" +document.getelementbyid ("Num1"). value+ "&num2=" +document.getelementbyid (" Num2 "). Value;
6 Xmlhttp.open ("GET", url,true);
7 Xmlhttp.onreadystatechange=showresult;
8 xmlhttp.send (NULL);
9}

3. Define a callback function to handle the information returned by the server

1//callback method
2function Showresult ()
3{
4 if (xmlhttp.readystate==4)
5 {
6 if (xmlhttp.status==200)
7 {
8 document.getElementById ("sum"). Value=xmlhttp.responsetext;
9}
10}
One} In the above example, it is the request sent by the client to the server's addhandler.ashx, and passes two parameters (that is, the number to be added) in the past, Let's see how the server handles the two parameters received over the past and how the addition operation is implemented and returns the result to the client. The code is as follows:
<%@ WebHandler language= "C #" class= "Handler"%>

Using System;
Using System.Web;
Using System.Data;
Using System.Data.SqlClient;

public class Handler:ihttphandler
{

public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
int a = Convert.ToInt32 (context. request.querystring["NUM1"]);
int B = Convert.ToInt32 (context. request.querystring["num2"]);
int result = a + B;
Context. Response.Write (Result);
}

public bool IsReusable
{
Get
{
return false;
}
}
}
Now we can call Addnumber () This method to send a request to the server to do a non-flush addition operation.
<div style= "Text-align:center" >
<br/> No Refresh summation example <br/>
<br/>
<input id= "NUM1" style= "width:107px" type= "text" onkeyup= "Addnumber ();" value= "0"/>
+<input id= "num2" style= "width:95px" type= "text" onkeyup= "Addnumber ();" value= "0"/>
=<input id= "sum" style= "width:97px" type= "text"/></div> run the result as follows:

This example is simple. The reason why I use this example is to introduce the process of XMLHTTP object. I'll download the project file later in the article.

------------------------------------------------------------------------------------------------------------
Above JS written to the page, in the actual project development is not recommended to do so, it is best to the JS code is defined to a JS file class. I have a XMLHttpRequest object of JS (downloaded online), All the relevant methods are basically written. Let's see how to use this external JS file to send asynchronous requests and responses.
I'll take a look at the detailed definition of this JS file:
1function Callbackobject ()
2{
3 this. XmlHttp = this. Gethttpobject ();
4}
5
6callbackobject.prototype.gethttpobject = function ()
7{
8 Var xmlhttp;
9 if (!xmlhttp && typeof XMLHttpRequest! = ' undefined '){
Ten try{
One xmlhttp = new XMLHttpRequest ();
catch (E){
XMLHTTP = false;
14}
15}
XMLHTTP return;
17}
18
19callbackobject.prototype.docallback = function (URL)
20{
if (this. XmlHttp)
22{
The IF (this. Xmlhttp.readystate = = 4 | | This. Xmlhttp.readystate = = 0)
24{
var othis = this;
. Xmlhttp.open (' POST ', URL);
this. Xmlhttp.onreadystatechange = function (){Othis.readystatechange ();};
this. Xmlhttp.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
this. Xmlhttp.send (NULL);
30}
31}
32}
33
34callbackobject.prototype.abortcallback = function ()
35{
The IF (this. XmlHttp)
PNS this. Xmlhttp.abort ();
38}
39
40callbackobject.prototype.onloading = function ()
41{
//Loading
43}
44
45callbackobject.prototype.onloaded = function ()
46{
//Loaded
48}
49
50callbackobject.prototype.oninteractive = function ()
51{
//Interactive
33;
54
55callbackobject.prototype.oncomplete = function (ResponseText, responsexml)
56{
//Complete
58}
59
60callbackobject.prototype.onabort = function ()
61{
+//Abort
63}
64
65callbackobject.prototype.onerror = function (status, StatusText)
66{
//Error
68}
69
70callbackobject.prototype.readystatechange = function ()
71{
if (this. Xmlhttp.readystate = = 1)
73{
this. Onloading ();
75}
if (this). Xmlhttp.readystate = = 2)
77{
this. OnLoaded ();
79}
The-else if (this. Xmlhttp.readystate = = 3)
81{
The. Oninteractive ();
83}
The else if (this. Xmlhttp.readystate = = 4)
$ {
if (this. Xmlhttp.status = = 0)
this. Onabort ();
The-else if (this. Xmlhttp.status = = && this. Xmlhttp.statustext = = "OK")
this. OnComplete (this. Xmlhttp.responsetext, this. Xmlhttp.responsexml);
All else
this. OnError (this. Xmlhttp.status, this. Xmlhttp.statustext, this. Xmlhttp.responsetext);
92}
733
94
A simple Hello instance:
<title>helloworld examples </title>
<script language= "JScript" src= "Callbackobject.js" ></script>
<script language=jscript>
function Createrequest ()
{
var name = Escape (document.getElementById ("name"). Value);
var CBO = new Callbackobject ();
Cbo. OnComplete = Cbo_complete;
Cbo.onerror = Cbo_error;
Cbo. DoCallback ("helloworldserver.aspx?name=" + name);
}

function Cbo_complete (responsetext, Responsexml)
{
alert (responsetext);
}

function Cbo_error (status, StatusText, ResponseText)
{
alert (responsetext);
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div style= "Display:inline; Font-weight:bold; font-size:30px; Font-family:arial, Verdana "
ms_positioning= "FlowLayout" >hello, ajax!</div>
<input type= "text" id= "name" >
<br>
<input type= "button" value= "Send Request" onclick= "Javascript:createrequest ()" >
</form>
</body>

About the XMLHttpRequest object is introduced here, more and more details please view the relevant information.
Welcome to make bricks, not very grateful!
This article example source code downloadCategory: [C#/asp.net/ajax]

Easily master the XMLHttpRequest object------"This is the. NET version"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.