AJAX client description, XMLHttpRequest object

Source: Internet
Author: User

You have used your own AJAX mechanism in the CommunityServer without using other auxiliary controls. The customer's XMLHttpRequest object encapsulation is sufficient for users to run AJAX in general browsers. Next, let's learn this story, hoping to help more people.

First of all, you need to understand the XMLHttp object in the browser:

XMLHTTP method:
Note: The client can use the XMLHTTP object to send any HTTP request, accept the HTTP response, and parse the XML document for the response.

Open Method: Initialize an Msxml2.XMLHTTP request, specifying the HTTP request method, URL, and authentication information.

Syntax:
Open (bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword)

Parameter introduction:

BstrMethod: data transmission method, that is, GET or POST.
BstrUrl: the URL of the Service webpage.
VarAsync: whether to run the command synchronously. The default value is True, that is, synchronous execution, but can only be performed in the DOM. Set it to False, that is, asynchronous execution.
BstrUser: user name, which can be omitted.
BstrPassword: user password, which can be omitted.

Send method: Send an HTTP request to the server and return a response.

Syntax:
OXMLHttpRequest. send (varBody)

Note: whether the method is synchronized depends on the varAsync parameter of the Open method. If it is set to True, It is synchronous, and the call is immediately returned. If it is set to False, the call is not returned until the entire response is received.

SetRequestHeader (bstrHeader, bstrvalue)

BstrHeader: HTTP header)
Bstrvalue: HTTP header value

If the Open method is defined as POST, you can define form upload:
Xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ")

XMLHTTP attributes:

Onreadystatechange: obtains the event handle of the returned result in synchronous execution mode. It can only be called in the DOM.
ResponseBody: returns an unsigned integer array.
ResponseStream: The returned result is an IStream stream.
ResponseText: returns a string.
ResponseXML: The returned result is in XML format.

Using this principle, you can also create a web thief program. Web Crawlers should be done by using this thing. However, I have never done it before. Maybe I will make a play in the near future, here we mainly look at how CS encapsulates it:

1 // Ajax Start
2/** // <summary>
3 // create a callback object. If the window. XMLHttpRequest () object exists, this object is returned. If it is IE, search for versions of Msxml2.XMLHTTP and Microsoft. XMLHTTP and create an object.
4 /// </summary>
5 function Ajax_GetXMLHttpRequest (){
6 if (window. XMLHttpRequest ){
7 return new XMLHttpRequest ();
8} else {
9 if (window. Ajax_XMLHttpRequestProgID ){
Return new ActiveXObject (window. Ajax_XMLHttpRequestProgID );
} Else {
Var progIDs = ["Msxml2.XMLHTTP. 5.0", "Msxml2.XMLHTTP. 4.0", "MSXML2.XMLHTTP. 3.0", "MSXML2.XMLHTTP", "Microsoft. XMLHTTP"];
For (var I = 0; I <progIDs. length; ++ I ){
Var progID = progIDs [I];
Try {
Var x = new ActiveXObject (progID );
Window. Ajax_XMLHttpRequestProgID = progID;
Return x;
} Catch (e ){
}
}
}
}
Return null;
}
/** // <Summary>
/// Ajax callback.
/// </Summary>
/// <Param name = "type"> the class that calls the server function includes the namespace (for example, NExplus. Controls. SiteHeader ). </Param>
/// <Param name = "id"> ID of the tag corresponding to the client (for example, <div id = "ID"> </div> ). </Param>
/// <Param name = "method"> name of the server (method) function (marked by AjaxMethod ). </Param>
/// <Param name = "args"> string uploaded to the server. </Param>
/// <Param name = "clientCallBack"> synchronous or asynchronous callback. </Param>
/// <Param name = "debugRequestText"> debug/request string. </Param>
/// <Param name = "debugResponseText"> debug/output a string. </Param>
/// <Param name = "debugErrors"> error message for debugging. </Param>
/// <Param name = "includeControlValuesWithCallBack"> whether the callback is performed with the control and its value. </Param>
/// <Param name = "url"> Url. </Param>
Function Ajax_CallBack (type, id, method, args, clientCallBack, debugRequestText, debugResponseText, debugErrors, includeControlValuesWithCallBack, url ){

If (! Url)
{
Url = window. location. href;
Url = url. replace (/\ #. * $/, ''); // remove the tag section in the URL, that is, the string after.
// Add the Ajax_CallBack parameter and set it to true, indicating AJAX callback.
If (url. indexOf ('? ')>-1)
Url + = "& Ajax_CallBack = true ";
Else
{
If (url. substr (url. length-1, 1) = "/")
Url + = "default. aspx ";

Url + = "? Ajax_CallBack = true ";
}
}

Var x = Ajax_GetXMLHttpRequest (); // gets the XMLHttpRequest object.
Var result = null;
If (! X ){
Result = {"value": null, "error": "NOXMLHTTP "};
If (debugErrors ){
Alert ("error:" + result. error );
}
If (clientCallBack ){
ClientCallBack (result );
}
Return result;
}

X. open ("POST", url, clientCallBack? True: false); // open the object in Post mode, so that the Request. Form can be used on the server to obtain parameters.
X. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8 ");
If (clientCallBack ){
// If synchronization is performed, the status is determined and an error message is output.
X. onreadystatechange = function (){
Var result = null;

If (x. readyState! = 4 ){
Return;
}

If (debugResponseText ){
Alert (x. responseText );
}

Try
{
Var result = eval ("(" + x. responseText + ")");
If (debugErrors & result. error ){
Alert ("error:" + result. error );
}
}
Catch (err)
{
If (window. confirm ('the following error occured while processing an AJAX request: '+ err. message +' \ n \ nwowould you like to see The response? '))
{
Var w = window. open ();
Using Doc ument. open ('text/plain ');
Using Doc ument. write (x. responseText );
Using Doc ument. close ();
}

Result = new Object ();
Result. error = 'an AJAX error occured. The response is invalid .';
}

ClientCallBack (result );
}
}
Var encodedData = "Ajax_CallBackType =" + type;
If (id ){
EncodedData + = "& Ajax_CallBackID =" + id. split ("$"). join (":");
}
EncodedData + = "& Ajax_CallBackMethod =" + method;
If (args ){
For (var I in args ){
EncodedData + = "& Ajax_CallBackArgument" + I + "=" + encodeURIComponent (args [I]);
}
}
// If the control is added, the control data is added.
If (includeControlValuesWithCallBack & document. forms. length> 0 ){
Var form = document. forms [0];
For (var I = 0; I <form. length; ++ I ){
Var element = form. elements [I];
If (element. name ){
Var elementValue = null;
If (element. nodeName = "INPUT "){
Var inputType = element. getAttribute ("TYPE"). toUpperCase ();
If (inputType = "TEXT" | inputType = "PASSWORD" | inputType = "HIDDEN "){
ElementValue = element. value;
} Else if (inputType = "CHECKBOX" | inputType = "RADIO "){
If (element. checked ){
ElementValue = element. value;
}
}
} Else if (element. nodeName = "SELECT "){
ElementValue = element. value;
} Else if (element. nodeName = "TEXTAREA "){
ElementValue = element. value;
}
If (elementValue ){
EncodedData + = "&" + element. name + "=" + encodeURIComponent (elementValue );
}
}
}
}
// If debugging is performed, the sent data is displayed.
If (debugRequestText ){
Alert (encodedData );
}
X. send (encodedData); // send data to the server.
If (! ClientCallBack ){
If (debugResponseText ){
Alert (x. responseText );
}
Result = eval ("(" + x. responseText + ")");
If (debugErrors & result. error ){
Alert ("error:" + result. error );
}
}
Delete x;
Return result;
}

// Ajax End
The rest do not need to be explained. It should be similar to reading comments. If there is something wrong, please criticize and advise. Thank you!

Related Article

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.