Ajax is a good thing, but it is not so convenient to use. The problem is summarized as follows:
The creation and usage methods are inconsistent on various browsers
Each browser has different caching strategies for responses
Browsers have cross-domain acquisition restrictions
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 relay proxy on the local server. Modello.ajax is the toolset that provides this solution.
Installation
Download Modello and Mdello.ajax
Unzip and put the three files modello.js, modello.ajax.js, jsproxy.php into any document directory of your server
Contain the two script files modello.js and modello.ajax.js in the html page
urlget method
Modello.ajax is very simple to use, please see the following example:
// Set cross-domain transfer proxy path Define('URLGET_PROXY', '/jsproxy.php'); // Powerful urlget method var urlget = Class.get('modello.ajax.Urllib').urlget; var url = '.. .'; // Synchronous GET method to obtain var response = urlget(url); // Synchronous POST method to obtain var data = '...'; var response = urlget(url, data); // Asynchronous POST method to obtain var callback = function (response) { // ...}var ret = urlget(url, data, callback); // Set request headers var headers = ["User-Agent: Modello.ajax's urlget"];var ret = urlget (url, data, callback, headers); // Use named channel var chunnel = '...'; var ret = urlget(url, data, callback, headers, chunnel); // Use Response object if (response.getStatus () == 200) { alert(response.getText());}// Set cross-domain transfer proxy path
Define('URLGET_PROXY', '/jsproxy.php');
// Powerful urlget method
var urlget = Class.get('modello.ajax.Urllib').urlget;
var url = '...';
// Synchronous GET Method to get
var response = urlget(url);
// Synchronous POST method to get
var data = '...';
var response = urlget(url, data);
// Asynchronous POST method to obtain
var callback = function (response) {
// ...
}
var ret = urlget(url, data, callback);
//Set request headers
var headers = ["User-Agent: Modello.ajax's urlget"];
var ret = urlget(url, data, callback, headers);
//Use named channel
var chunnel = '...';
var ret = urlget(url, data, callback, headers, chunnel);
//Use Response Object
if (response.getStatus() == 200) {
alert(response.getText());
}
urlget The explanation of each parameter is as follows:
url: URL address of the target resource.
data: POST data. If data is empty, use the GET method to obtain it.
callback: Get the callback function asynchronously. If callback is empty, synchronous acquisition is used.
headers: Additional request headers. This is an array, each item is a string, set a line header, and a carriage return is not allowed at the end of the string.
chunnel: Named channel. Used to reuse a connection channel.
Return value of urlget:
If it is obtained synchronously, the Response object will be returned successfully, and false will be returned if it fails. If it is acquired asynchronously, true will be returned successfully, and the callback function will be called after acquisition, and false will be returned if failed. If a named channel is specified but the channel is occupied by other requests, both synchronous and asynchronous will return false.
Parameters of the callback function:
response: Response object.
chunnel: The named channel specified when calling.
Response object
Response object is used to access various data items of the response.It provides the following interface:
response.getStatus(); // HTTP response code (integer) response.getStatusText(); // Literal interpretation of response code response.getHeader(key); // Specified by key The header data of the response response.getAllHeaders(); // All the header data of the response (excluding the status line) response.getRawHeader(); // The original header data of the response (including the status line) response.getText() ; // The body data of the response response.getXML(); // The body data of the response is formatted as an Xml Document object response.getStatus(); // HTTP response code (integer)
response.getStatusText(); // Literal explanation of response code
response.getHeader(key); // Header data of the response specified by key
response.getAllHeaders(); // All header data of the response (excluding status line )
response.getRawHeader(); // The original header data of the response (including status line)
response.getText(); // The body data of the response
response.getXML(); // The response body data is formatted as an Xml Document object
In most cases, using the urlget function is sufficient, and it can be used across browsers and domains. If you want to do some lower-level operations, Modello.ajax provides you with two base classes for cross-browser use: Connection and Request
Connection class
This is a static class that provides cross-browser The method returns an XMLHTTPRequest object. The usage method is as follows:
/* * Returns a cross-browser version of XMLHTTPRequest object successfully, * returns null on failure. */var conn = Class.get('modello.ajax.Connection').get();/*
* Returns a cross-browser version of XMLHTTPRequest object successfully,
* returns null on failure.
*/
var conn = Class.get('modello.ajax.Connection').get();
Request class
This is an encapsulation of the XMLHTTPRequest object, making it easier to It uses an interface and solves the problem of browser response caching, but it does not have the function of cross-domain acquisition. The properties and methods provided by Request are as follows:
/* * Path to class */var Request = Class.get('modello.ajax.Request'); /* * Create instance * url, method, data are all For optional parameters */var request = new Request([url[, method[, data]]]); /* * Set the URL */request.setURL(url); /* * Set the acquisition method. Currently supported: GET, POST, HEAD */request.setMethod(method); /* * Set the acquisition method.Currently supported: GET, POST, HEAD */request.setData(data); /* * Set callback function * The prototype of the callback function is: * var callback = function (response) {}; */request.setHandler(handler); /* * Set request header */request.setHeader(key, value); /* * Add request header */request.addHeader(header); /* * Send request * async is true, use asynchronous mode * Used by default Synchronous method * If the call is successful, the synchronous method will return the response object, and the asynchronous method will return true * If the call fails, it will return false */request.open([async]); /* * Query the status of the current request * Return a string description, possibly For: * Uninitialized: not initialized * Loading: initialized * Loaded: sending data * Interactive: data transferring * Complete: completed */request.getState(); /* * Returns the currently used Connection object */request.getConnection() ; /* * Return the Response object * If the current request status is not Complete, return null */request.getResponse(); /* * Abort the current request */request.abort(); /* * Clean up all request headers * /request.reset(); /* * In addition to the above methods, 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 instance
* url, method, data are all optional parameters
*/
var request = new Request([url[, method[, data]]]);
/*
* Set URL
*/
request.setURL(url);
/*
* Set the acquisition method. Currently supported: GET, POST, HEAD
*/
request.setMethod(method);
/*
* Set the acquisition method. Currently supported: GET, POST, HEAD
*/
request.setData(data);
/*
* Set callback function
* The prototype of the callback function is:
* var callback = function (response) {};
*/
request.setHandler(handler);
/*
* Set request header
*/
request.setHeader(key, value);
/*
* Add request header
*/
request.addHeader(header);
/*
* Send request
* async is true, use asynchronous method
* Use synchronous method by default
* If the call is successful, the synchronous method returns the response object, and the asynchronous method returns true
* If the call fails, uniform return false
*/
request.open([async]);
/*
* Query the status of the current request
* Return a string description, which may be:
* Uninitialized: Not initialized
* Loading: Initialized
* Loaded: Sending data
* Interactive: Data is being transferred
* Complete: Completed
*/
request.getState() ;
/*
* Returns the currently used Connection object
*/
request.getConnection();
/*
* Returns the Response object
* If the current request status is not Complete, return null
*/
request.getResponse();
/*
* Abort the current request
*/
request.abort();
/*
* Clear all request headers
*/
request.reset();
/*
* except In 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-domain calls, Modello.ajax uses a relay proxy on the local server. Using the proxy method eliminates the need to make special settings for individual browsers, does not rely on specific servers, and has the advantages of scalability and other advantages. The proxy provided with the Modello.ajax tool set is written in PHP and can be installed on any server that can run PHP.Proxy can also be written in other languages. Modello.ajax plans to provide a python version of jsproxy in subsequent versions. The design of jsproxy is described below. Friends in need can refer to it to implement other language versions of jsproxy.
jsproxy receives three POST parameters: url, data, headers. url is the URL address of the target resource; data is the POST data. If it is empty, use the GET method to obtain the resource; headers are the additional request header data. jsproxy obtains the target resource based on these parameters, and then forwards all received response headers and response bodies to the requester. The parameters received by jsproxy are sent by Modello.ajax, and the character set is UTF-8. Please pay attention to this when processing. There are many possible character sets for the response obtained by jsproxy. Before forwarding the response, jsproxy should automatically detect the character set of the current response and indicate it in the forwarded response header. If this step is ignored, the response received by the requester may be garbled.
urlparse, urljoin functions
URL processing functions like urlparse, urljoin are very common in other scripting languages, but not in JavaScript. Modello.ajax provides these two functions, which are used internally by the urlget function mentioned earlier. The following explains their usage:
/* * urlparse: URL analysis function */var url = 'http://user:pass@host:port/path?query#flagment';var ret = Class .get('modello.ajax.Ullib').urlparse(url);// At this time // ret.user == 'user'// ret.pass == 'pass'// ret.host == 'host '// ret.post == 'post', default is 80// ret.path == 'path', starting with '/' // 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.Ullib') .urlparse(url);
// At this time
// ret.user == 'user'
// ret.pass == 'pass'
// ret.host == ' host'
// ret.post == 'post', default is 80
// ret.path == 'path', starting with '/'
// 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.Ullib').urljoin(url1, url2);
// At this time
// url == 'http://www.example.com/index.html'
Summary
Everything provided by Modelello.ajax has been described , hope it can help you speed up the development of Ajax applications ;)