Ajax cross-origin tool: modello. Ajax

Source: Internet
Author: User
Ajax cross-origin tool: modello. Ajax

Problem
Ajax is a good thing, but it is not so convenient to use. The problem is summarized as follows:

  • The creation method and usage method on various browsers are inconsistent
  • Different browsers have different cache policies for responses.
  • Browser cross-origin access restriction

The first two problems can be solved by encapsulating the XMLHTTPRequest object. There are many solutions to the third problem. The better compatibility and portability is to place a transit proxy on the Local Domain Server. Modello. Ajax is a tool set that provides this solution.

Install
Download modello and mdello. Ajax

Decompress the package and put the modello. JS, modello. Ajax. JS, and jsproxy. php files into any file directory on your server.
The HTML page contains the modello. js and modello. Ajax. js script files.
Urlget Method
Modello. Ajax is very simple to use. See the following example:

Program code // set the cross-origin transit proxy path
Define ('urlget _ proxy', '/jsproxy. php ');

// Powerful urlget Method
VaR urlget = Class. Get ('modello. Ajax. urllib'). urlget;

VaR url = '... ';

// Obtain the synchronous get Method
VaR response = urlget (URL );

// Obtain the synchronous POST method
VaR DATA = '... ';
VaR response = urlget (URL, data );

// Obtain the asynchronous POST method
VaR callback = function (response ){
//...
}
VaR ret = urlget (URL, Data, callback );

// Set the Request Header
VaR headers = ["User-Agent: modello. Ajax's urlget"];
VaR ret = urlget (URL, Data, callback, headers );

// Use the named Channel
VaR chunnel = '... ';
VaR ret = urlget (URL, Data, callback, headers, Chunnel );

// Use the response object
If (response. getstatus () = 200 ){
Alert (response. gettext ());
} // Set the cross-origin transit proxy path
Define ('urlget _ proxy', '/jsproxy. php ');
// Powerful urlget Method
VaR urlget = Class. Get ('modello. Ajax. urllib'). urlget;
VaR url = '... ';
// Obtain the synchronous get Method
VaR response = urlget (URL );
// Obtain the synchronous POST method
VaR DATA = '... ';
VaR response = urlget (URL, data );
// Obtain the asynchronous POST method
VaR callback = function (response ){
//...
}
VaR ret = urlget (URL, Data, callback );
// Set the Request Header
VaR headers = ["User-Agent: modello. Ajax's urlget"];
VaR ret = urlget (URL, Data, callback, headers );
// Use the named Channel
VaR chunnel = '... ';
VaR ret = urlget (URL, Data, callback, headers, Chunnel );
// Use the response object
If (response. getstatus () = 200 ){
Alert (response. gettext ());
}

The urlget parameters are described as follows:
URL: the URL of the target resource.
Data: Post Data. If data is null, use the get method to obtain the data.
Callback: gets the callback function asynchronously. If callback is empty, use synchronous retrieval.
Headers: append the request header. This is an array. each item is a string and a line of header is set. line breaks cannot be carried at the end of the string.
Chunnel: Name channel. Used to reuse a connection channel.
Urlget return value:
If it is obtained synchronously, the response object is returned successfully. If it fails, false is returned. If the result is obtained asynchronously, true is returned successfully, and the callback function is called after the result is obtained. If the result is failed, false is returned. If a named channel is specified, but the channel is being occupied by other requests, both synchronous and asynchronous return false.
Callback function parameters:
Response: Response object.
Chunnel: The name channel specified during the call.
Response object
The response object is used to access various data items in the response. It provides the following interfaces:
Response. getstatus (); // HTTP response code (integer)
Response. getstatustext (); // literal explanation of the response code
Response. getheader (key); // response header data specified by the key
Response. getallheaders (); // all response header data (excluding status rows)
Response. getrawheader (); // response's original header data (including status rows)
Response. gettext (); // response body data
Response. getxml (); // The response body data is formatted as the XML Document Object response. getstatus (); // HTTP response code (integer)
Response. getstatustext (); // literal explanation of the response code
Response. getheader (key); // response header data specified by the key
Response. getallheaders (); // all response header data (excluding status rows)
Response. getrawheader (); // response's original header data (including status rows)
Response. gettext (); // response body data
Response. getxml (); // The response body data is formatted as an XML document object.

In most cases, the urlget function is sufficient, and can be used across browsers and cross-domains. If you want to perform more underlying operations, modello. Ajax provides two base classes for cross-browser use: Connection and request.
Connection class
This is a static class that provides cross-browser methods to return an XMLHTTPRequest object. The usage is as follows:

Program code /*
* A cross-browser XMLHTTPRequest object is returned,
* If a failure occurs, null is returned.
*/
VaR conn = Class. Get ('modello. Ajax. connection'). Get ();/*
* A cross-browser XMLHTTPRequest object is returned,
* If a failure occurs, null is returned.
*/
VaR conn = Class. Get ('modello. Ajax. connection'). Get ();

Request class
This is an encapsulation of the XMLHTTPRequest object. It provides easier-to-use interfaces and solves the browser's issue of response caching, but does not provide cross-origin retrieval. The attributes and methods provided by request are as follows:
/*
* Class path
*/
VaR request = Class. Get ('modello. Ajax. request ');

/*
* Create an instance
* URL, method, and data are optional parameters.
*/
VaR request = new request ([url [, method [, data]);

/*
* Set URL
*/
Request. seturl (URL );

/*
* Set the obtaining method. Currently, get, post, and head are supported.
*/
Request. setmethod (method );

/*
* Set the obtaining method. Currently, get, post, and head are supported.
*/
Request. setdata (data );

/*
* Set the callback function
* The callback function is prototype:
* Var callback = function (response ){};
*/
Request. sethandler (handler );

/*
* Set the Request Header
*/
Request. setheader (Key, value );

/*
* Add a Request Header
*/
Request. addheader (header );

/*
* Send a request
* If async is set to true, asynchronous mode is used.
* Synchronization mode is used by default.
* The call is successful. The response object is returned in synchronous mode and true is returned in asynchronous mode.
* If the call fails, false is returned.
*/
Request. Open ([async]);

/*
* Query the status of the current request
* Returns a string description, which may be:
* Uninitialized: not initialized
* Loading: initialization
* Loaded: send data
* Interactive: data transmission in progress
* Complete: complete
*/
Request. getstate ();

/*
* Returns the currently used connection object.
*/
Request. getconnection ();

/*
* Response object
* If the current request status is not complete, null is returned.
*/
Request. getresponse ();

/*
* Abort the current request
*/
Request. Abort ();

/*
* Clear all request headers
*/
Request. Reset ();

/*
* In addition to the above method, you can also set event processing functions for the request object.
* There are a total of the following events:
*/

Request. onexception = function (){};
Request. onloading = function (){};
Request. onloaded = function (){};
Request. oninteractive = function (){};
Request. oncomplete = function (){};/*
* Class path
*/
VaR request = Class. Get ('modello. Ajax. request ');
/*
* Create an instance
* URL, method, and data are optional parameters.
*/
VaR request = new request ([url [, method [, data]);
/*
* Set URL
*/
Request. seturl (URL );
/*
* Set the obtaining method. Currently, get, post, and head are supported.
*/
Request. setmethod (method );
/*
* Set the obtaining method. Currently, get, post, and head are supported.
*/
Request. setdata (data );
/*
* Set the callback function
* The callback function is prototype:
* Var callback = function (response ){};
*/
Request. sethandler (handler );
/*
* Set the Request Header
*/
Request. setheader (Key, value );
/*
* Add a Request Header
*/
Request. addheader (header );
/*
* Send a request
* If async is set to true, asynchronous mode is used.
* Synchronization mode is used by default.
* The call is successful. The response object is returned in synchronous mode and true is returned in asynchronous mode.
* If the call fails, false is returned.
*/
Request. Open ([async]);
/*
* Query the status of the current request
* Returns a string description, which may be:
* Uninitialized: not initialized
* Loading: initialization
* Loaded: send data
* Interactive: data transmission in progress
* Complete: complete
*/
Request. getstate ();
/*
* Returns the currently used connection object.
*/
Request. getconnection ();
/*
* Response object
* If the current request status is not complete, null is returned.
*/
Request. getresponse ();
/*
* Abort the current request
*/
Request. Abort ();
/*
* Clear all request headers
*/
Request. Reset ();
/*
* In addition to the above method, you can also set event processing functions for the request object.
* There are a total of the following events:
*/
Request. onexception = function (){};
Request. onloading = function (){};
Request. onloaded = function (){};
Request. oninteractive = function (){};
Request. oncomplete = function (){};

Jsproxy
For cross-origin calls, modello. Ajax sets a transit proxy on the Local Domain Server. Using proxy, you do not need to make special settings for individual browsers, do not rely on specific servers, and have the advantages of scalability. The proxy provided with the modello. Ajax toolset is written in PHP, and can be installed on all servers that can run php. The proxy can also be written in other languages. modello. Ajax plans to provide the Python version of jsproxy in later versions. The following describes the jsproxy design. If you need it, you can refer to it to implement jsproxy in other languages.
Jsproxy receives three post parameters: URL, data, and headers. The URL is the URL address of the target resource, the data is post data, if it is null, use the get method to obtain the resource, and the request header data appended to headers. Based on these parameters, jsproxy obtains the target resource and forwards all received response headers and response bodies to the requester. The parameters received by jsproxy are issued by modello. Ajax and the character set is UTF-8. Pay attention to this when dealing with them. Jsproxy has many possible response character sets. before forwarding a response, jsproxy should automatically detect the current response character set and specify it in the response header. If this step is ignored, the response received by the requester may be garbled.
Urlparse, urljoin Function
URL Processing functions such as urlparse and urljoin are common in other scripting languages, but not in JavaScript. Modello. Ajax provides these two functions. The urlget function mentioned above uses these two functions internally. The following describes their usage:

Program code /*
* Urlparse: URL Analysis Function
*/
VaR url = 'HTTP: // User: Pass @ host: Port/path? Query # flagment ';
VaR ret = Class. Get ('modello. Ajax. urllib'). urlparse (URL );
// At this time
// Ret. User = 'user'
// Ret. Pass = 'pass'
// Ret. Host = 'host'
// Ret. Post = 'post'. The default value is 80.
// Ret. Path = 'path', starting '/'
// Ret. query = 'query'
// Ret. flagment = 'flagment'

/*
* Urljoin: merge two URLs.
*/
VaR url1 = 'HTTP: // www.example.com/about/about.html ';
VaR url2 = '/index.html ';
VaR url = Class. Get ('modello. Ajax. urllib'). urljoin (url1, url2 );
// At this time
// URL = 'HTTP: // www.example.com/index.html '/*
* Urlparse: URL Analysis Function
*/
VaR url = 'HTTP: // User: Pass @ host: Port/path? Query # flagment ';
VaR ret = Class. Get ('modello. Ajax. urllib'). urlparse (URL );
// At this time
// Ret. User = 'user'
// Ret. Pass = 'pass'
// Ret. Host = 'host'
// Ret. Post = 'post'. The default value is 80.
// Ret. Path = 'path', starting '/'
// Ret. query = 'query'
// Ret. flagment = 'flagment'
/*
* Urljoin: merge two URLs.
*/
VaR url1 = 'HTTP: // www.example.com/about/about.html ';
VaR url2 = '/index.html ';
VaR url = Class. Get ('modello. Ajax. urllib'). urljoin (url1, url2 );
// At this time
// URL = 'HTTP: // www.example.com/index.html'

 

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.