Ajax core framework functions and Examples

Source: Internet
Author: User

Core ajax (options) functions include setting up xmlhttprequest, extracting data, and determining whether the response is successful. These functions basically meet daily requirements. Copy codeThe Code is as follows: // A generic function for processing mming AJAX requests
// It takes one argument, which is an object that contains a set of options
// All of which are outline in the comments, below
Function ajax (options ){
// Load the options object with defaults, if no
// Values were provided by the user
Options = {
// The type of HTTP Request
Type: options. type | "POST ",
// The URL the request will be made
Url: options. url | "",
// How long to wait before considering the request to be a timeout
Timeout: options. timeout || 5000,
// Functions to call when the request fails, succeeds,
// Or completes (either fail or succeed)
OnComplete: options. onComplete | function (){},
OnError: options. onError | function (){},
OnSuccess: options. onSuccess | function (){},
// The data type that'll be returned from the server
// The default is simply to determine what data was returned from
// And act accordingly.
Data: options. data | ""
};
// Create the request object
Var xml = new XMLHttpRequest ();
// Open the asynchronous POST request
// Xml. open ("GET", "/some/url. cgi", true );
Xml. open ("GET", options. url, true );
// We're going to wait for a request for 5 seconds, before giving up
Var timeoutLength = 5000;
// Keep track of when the request has been succesfully completed
Var requestDone = false;
// Initalize a callback which will fire 5 seconds from now, canceling
// The request (if it has not already occurred ).
SetTimeout (function (){
RequestDone = true;
}, TimeoutLength );
// Watch for when the state of the document gets updated
Xml. onreadystatechange = function (){
// Wait until the data is fully loaded,
// And make sure that the request hasn't already timed out
If (xml. readyState = 4 &&! RequestDone ){
// Check to see if the request was successful
If (httpSuccess (xml )){
// Execute the success callback with the data returned from the server
Options. onSuccess (httpData (xml, options. type ));
// Otherwise, an error occurred, so execute the error callback
} Else {
Options. onError ();
}
// Call the completion callback
Options. onComplete ();
// Clean up after ourselves, to avoid memory leaks
Xml = null;
}
};
// Establish the connection to the server
Xml. send ();
// Determine the success of the HTTP response
Function httpSuccess (r ){
Try {
// If no server status is provided, and we're actually
// Requesting a local file, then it was successful
Return! R. status & location. protocol = "file:" |
// Any status in the 200 range is good
(R. status >=200 & r. status <300) |
// Successful if the document has not been modified
R. status = 304 |
// Safari returns an empty status if the file has not been modified
Navigator. userAgent. indexOf ("Safari")> = 0 & typeof r. status = "undefined ";
} Catch (e ){}
// If checking the status failed, then assume that the request failed too
Return false;
}
// Extract the correct data from the HTTP response
Function httpData (r, type ){
// Get the content-type header
Var ct = r. getResponseHeader ("content-type ");
// If no default type was provided, determine if some
// Form of XML was returned from the server
Var data =! Type & ct. indexOf ("xml")> = 0;
// Get the XML Document object if XML was returned from
// The server, otherwise return the text contents returned by the server
Data = type = "xml" | data? R. responseXML: r. responseText;
// If the specified type is "script", execute the returned text
// Response as if it was JavaScript
If (type = "script ")
Eval. call (window, data );
// Return the response data (either an XML Document or a text string)
Return data;
}
}

In the same directory, we can create an rss. xml file and use this function to access it.
Rss. xml is as follows:Copy codeThe Code is as follows: <titles>
<Title>
Fate
</Title>
<Title>
Moon
</Title>
<Title>
Fate moon
</Title>
</Titles>

Create an html document and call it to see that the content in rss. xml can be accessed.
Overall, it is really simple and simple. Not only can files in xml format be accessed, but files in html and. js formats can be called;
You can create and call corresponding files locally.

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.