Cross-Browser settings innerHTML method _javascript Tips

Source: Internet
Author: User
Tags function prototype gettext response code static class domain server

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

Inconsistent ways to create and use on various browsers
Each browser has a different caching policy for the response
Cross-domain access restrictions for browsers
The first two problems can be solved by encapsulating the XMLHttpRequest object, and the third problem is solved in many ways, compatibility and portability is better than placing a relay proxy on the domain server. Modello.ajax is the set of tools that provide this suite of solutions.

Installation
Download Modello and Mdello.ajax
Unzip and Modello.js, Modello.ajax.js, jsproxy.php these three files into any document directory on your server
Include both the modello.js and Modello.ajax.js script files in the HTML page
Urlget method
Modello.ajax is very simple to use, please see the following example:

  Set cross-domain relay  proxy  path define (' Urlget_proxy ',  '/jsproxy.php '); //  powerful  urlget   Method Var urlget = class.get (' Modello.ajax.Urllib ') .urlget; var url =  ' ... '; //  sync  GET  method gets Var response = urlget (URL); //  sync  post   Methods 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 Head var headers =  ["User-agent: modello.ajax ' S urlget"];var ret = urlget (url, data,  callback, headers); //  using named Channels var chunnel =  ' ... '; var ret = urlget (url, data, callback, headers, chunnel); //  use  Response  object if  ( Response.getstatus () == 200)  {    alert (Response.gettext ());}   Set cross-domain relay  proxy  path
Define (' Urlget_proxy ', '/jsproxy.php ');

A powerful Urlget method
var urlget = class.get (' Modello.ajax.Urllib '). Urlget;

var url = ' ... ';

The synchronization get method gets the
var response = urlget (URL);

The synchronous POST method gets
var data = ' ... ';
var response = urlget (URL, data);

The asynchronous POST method gets
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);

Using named channels
var Chunnel = ' ... ';
var ret = urlget (URL, data, callback, headers, Chunnel);

Using the Response object
if (response.getstatus () = = 200) {
Alert (Response.gettext ());
}

Urlget the various parameters are explained as follows:

URL: The URL address of the target resource.
Data:post data. If data is empty, the Get method is used to obtain the.
Callback: Gets the callback function asynchronously. If callback is empty, synchronization is used to obtain it.
Headers: Attach request head. This is an array, each item is a string, set a line of head, the end of the string can not be wrapped with a carriage return.
Chunnel: Named Channel. Used to reuse a connection channel.
Urlget return Value:

If it is a synchronous fetch, the Response object is successfully returned, and the failure returns false. If it is an asynchronous fetch, returns true successfully, and the callback function is invoked after fetching, and the failure returns false. If a named channel is specified, but the channel is being consumed by another request, both synchronous and asynchronous return false.

Parameters for the callback function:

Response:response object.
Chunnel: The named channel specified at the time of the call.
Response objects
The Response object is used to access the individual data items of the response. It provides the following interface:

Response.getstatus (); HTTP Response Code (integer) Response.getstatustext ();  The literal interpretation of the response code Response.getheader (key); The header data for the response specified by Key response.getallheaders ();  All header data for the response (not including 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 XML Document object Response.getstatus (); HTTP Response Code (integer)
Response.getstatustext (); Literal interpretation of response codes
Response.getheader (key); Header data for the response specified by key
Response.getallheaders (); All header data for the response (does not contain a status line)
Response.getrawheader (); The original header data for the response (contains the status line)
Response.gettext (); Body data of the response
Response.getxml (); The body data of the response is formatted as an XML Document object

In most cases, the Urlget function is sufficient to handle, and it can be used across domains in a cross-browser. If you want to do some low-level operations, Modello.ajax provides you with two base classes for use across browsers: Connection and Request

Connection class
This is a static class that provides a cross-browser way to return a XMLHttpRequest object. Use the following methods:

/* * Successfully returned a cross-browser version of the XMLHttpRequest object, * failed to return NULL. */var conn = class.get (' modello.ajax.Connection '). Get ()/*
* Successfully returns a cross-browser version of the XMLHttpRequest object,
* Failed to return NULL.
*/
var conn = class.get (' modello.ajax.Connection '). get ();

Request class
This encapsulates the XMLHttpRequest object, provides a more easy-to-use interface, and resolves browser-response caching problems, but does not have cross-domain acquisition capabilities. The properties and methods provided by Request are as follows:

The path of the/* *  class  */var request = class.get (' Modello.ajax.Request ');  /* *   Create an instance  * url, method, data  all optional Parameters  */var request = new  Request ([Url[, method[, data]]]); /* *  set  url */request.seturl (URL);  / * *  sets the Fetch method. Currently supported: Get, post, head */request.setmethod (method); /* *  set fetch methods. Current support: Get, post, head */request.setdata (data); /* *  set the callback function  *  callback function prototype as:  * var callback = function  (response)  {}; */request.sethandler (handler ; /* *  Set Request Head  */request.setheader (key, value); /* *  increase request Head  */ Request.addheader (header); /* *  send request  * async  for  true, use asynchronous mode  *  Default use of sync mode  *  successful call, synchronous return  response  object, asynchronous return  true *  call failed, unified return  false  */request.open ([async]; /* *  queries the status of the current request  *  returns a string description, possibly:  * uninitialized: uninitialized  *  Loading: Initializing  * loaded: Sending data  * interactive:  * complete in data transfer: Completing  */ Request.getstate (); /* *  returns the currently used  Connection  object  */request.getconnection ();  / * *  return  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 set the event handler function  *  A total of the following events in the  Request  object  */  request.onexception = function ()  {};request.onloading = function ()  {}; Request.onloaded = function ()  {};request.oninteractive = function ()  {}; Request.oncomplete = function ()  {};/*
* The path of the class
*/
var Request = class.get (' modello.ajax.Request ');

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

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

/*
* Set the Fetch method. Current support: Get, POST, head
*/
Request.setmethod (method);

/*
* Set the Fetch method. Current support: 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 Head
*/
Request.setheader (key, value);

/*
* Increase request Head
*/
Request.addheader (header);

/*
* Send Request
* Async is True, using asynchronous methods
* The default synchronization mode is used
* Successful call, return response object synchronously, return true asynchronously
* Call failed, unified return False
*/
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: In data transfer
* Complete: Complete
*/
Request.getstate ();

/*
* Returns the Connection object currently in use
*/
Request.getconnection ();

/*
* Return Response Object
* Returns NULL if the current request state is not Complete
*/
Request.getresponse ();

/*
* Abort Current request
*/
Request.abort ();

/*
* Clear All Request headers
*/
Request.reset ();

/*
* In addition to the above method, you can also set the event handler function on the Request object
* There are a total of the following kinds of 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 in this domain server. Using proxy means that you do not have 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 by the server running PHP. Proxy can also be written in other languages, and Modello.ajax has plans to provide Python version of Jsproxy in subsequent versions. The following describes the design of Jsproxy, the need for friends can refer to the implementation of other language versions of the Jsproxy.

Jsproxy receives three POST parameters: URL, data, headers. The URL is the URL of the target resource, data is post, and if NULL, the Get method is used to obtain the resource; Headers the additional request header data. Jsproxy the target resource according to these parameters, and then forwards all the received response headers and response body parts to the requestor. Jsproxy received the parameters are issued by the Modello.ajax, character set for UTF-8, when processing to pay attention to this point. There are many possibilities for the character set of the response that Jsproxy obtains, before forwarding the response jsproxy should automatically detect the character set of the current response and indicate in the forwarded response header. If suddenly this step, the requestor received a response may be garbled.

Urlparse, Urljoin function
Urlparse, URL handlers like urljoin are 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. Here's how to explain their usage:

* * Urlparse:url parse 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 = = ' P OST ', default for 80//Ret.path = = ' path ', with '/' beginning//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);
When
Ret.user = = ' user '
Ret.pass = ' Pass '
Ret.host = ' Host '
Ret.post = ' post ', defaults to 80
Ret.path = = ' path ', beginning 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);
When
url = = ' http://www.example.com/index.html '

Summarize
All the things Modello.ajax has already described, hopefully it will help you accelerate the development of AJAX applications;

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.