Recently, due to project requirements, I focused on Ajax-related programming. I initially wanted to use prototype, jquery, and other frameworks. Later I found that I didn't actually use so much content in these frameworks, forcible use can only drag visitors to my website and reduce user experience. Therefore, I decided to write a set of Ajax code libraries suitable for my own needs. In this Ajax code library, the following functions are implemented: 1. Ajax remotely calls data 2. Submits form forms asynchronously through Ajax 3. After data is returned, ability to bind data to the relevant controls of the page (such as Div, select, UL, span, etc.) 4. Allow the Ajax program to support the browser's forward and backward buttons
1. What is Ajax? What can he do?
Ajax is called "Asynchronous JavaScript and XML" (non-synchronous JavaScript and XML). It is a Web page development technology used to create interactive web applications. The biggest advantage of AJAX is that data can be maintained without updating the entire page. This allows web applications to respond quickly to user actions and avoid sending unchanged information on the network. Ajax does not require any browser plug-ins, but users need to allow JavaScript to be executed on the browser. As with DHTML applications, Ajax applications must
Different browsers and platforms have undergone rigorous tests. With the maturity of Ajax, some libraries that simplify Ajax usage have also been released. Similarly, there is another technology that AIDS program design.
Some users that do not support JavaScript provide alternative functions.
Ii. Core code
The so-called core code is to provide a cross-browser Ajax call code, this part of the code is necessary for subsequent code extension, in this part of the code, we provide a method for creating an XMLHTTPRequest object and performing asynchronous data exchange with the Web server. In the code I wrote, two related functions are customized. One is the universal function for getting HTML objects, and the other is to automatically filter spaces at the beginning and end of a string. The Code is as follows: function $ (elementid ){
Return document. getelementbyid (elementid );
}
Function trim (STR) {// Delete spaces between the left and right sides
Return Str. Replace (/(^/S *) | (/S * $)/g ,"");
} The core Ajax code is as follows :/*
* Obtain Ajax Objects Based on Different browsers
*/
Function getajaxobject (){
VaR XMLHttpRequest;
// Determine whether to implement XMLHttpRequest as a local JavaScript Object
If (window. XMLHttpRequest ){
XMLHttpRequest = new XMLHttpRequest ();
} Else if (window. activexobject) {// determines whether ActiveX controls are supported
Try {
// Create an XMLHTTPRequest object by instantiating a new instance of activexobject
XMLHttpRequest = new activexobject ("Microsoft. XMLHTTP"); // msxml3 or a later version
} Catch (e ){
Try {
// Create an XMLHTTPRequest object by instantiating a new instance of activexobject
XMLHttpRequest = new activexobject ("msxml2.xmlhttp"); // versions earlier than msxml3
} Catch (e ){}
}
}
If (! XMLHttpRequest ){
Alert ("failed to Create Ajax object, you will not be able to browse the webpage ");
}
Return XMLHttpRequest;
}
/*
* Submit a request asynchronously.
*/
Function sendrequestbyajax (method, URL, Data, datahandler ){
// Obtain the Ajax object
Request = getajaxobject ();
// Set the callback function
If (! Ie4 ){
Request. onload = datahandler;
} Else {
Request. onreadystatechange = datahandler;
}
Request. Open (method, URL, true); // true indicates that the asynchronous method is used. False indicates that the synchronous method is used.
// Processing and submission method
If ("get" = method. tolowercase ()){
// Use get to submit data
VaR URLs = URL. Split ("? ");
If (URLs [1] = "" | typeof (URLs [1]) = "undefined "){
Url = URLs [0] + "? "+ Data;
} Else {
Url = URLs [0] + "? "+ URLs [1] +" & "+ data;
}
Data = NULL; // For get method, request must be empty
} Else if ("Post" = method. tolowercase ()){
// Use post to submit data
Request. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
}
Request. Send (data );
}
Iii. Callback functions and data parsing
Jesse James, Ajax author
Garret suggests that AJAX uses XHTML + CSS to represent information and JavaScript to operate dom (Document Object
Model) for Dynamic Display and interaction, using XML and XSLT for data exchange and related operations, because operabrowser does not support XSLT format objects or XSLT
Generally, XML is used for data transmission. Some attributes of the request are displayed in the callback function. The value is readystate, which provides the ready status of the current HTML.
0: the request is not initialized.
1: The request has been created but has not been sent (send () has not been called ())
2: The request has been sent and is being processed. (You can obtain the Content Header from the response)
3: When a request is being processed, some data in the response is usually available.
4: The response has been completed.
Status: provides the status code of the current HTML.
401: unauthorized
403: Access prohibited
404: no access page found
200: the normal callback function is as follows :/*
* The callback function in XML format is returned.
*/
Function xmlcallback (){
// Data reception completed
If (request. readystate = 4 ){
// Receive data normally
If (request. Status = 200 ){
// Call the XML file parsing function
Parsexmlmessage ();
} Else {
// Display the error message
Alert ("not able to retrieve description" + request. statustext );
}
}
}
/*
* XML file parsing functions
*/
Function parsexmlmessage (){
// Obtain the returned XML file
VaR xmldoc=request.responsexml.doc umentelement;
// Parse the XML file
Parsexml ("elementid", xmldoc );
}
/*
* Parse XML files
* @ Param elementid ID of the object to bind data
* @ Param xmldoc the XML file to be parsed
*/
Function parsexml (elementid, xmldoc) {// here, the XML file format is modified based on your custom
VaR xmlroot = xmldoc. getelementsbytagname ("items ");
VaR datatype = xmlroot [0]. getattribute ("datatype ");
VaR items = xmldoc. getelementsbytagname ('item ');
Switch (datatype. tolowercase ()){
Case "array ":
// The returned object is the result set.
Binditems (elementid, items );
Break;
Case "string ":
// The returned object is a string
Bindtext (elementid, items [0]. childnodes [0]. firstchild. nodevalue );
}
} If an HTML page is returned after Ajax is called, you can use the following callback function :/*
* HTML file parsing functions
*/
Function htmlcallback (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
Parsehtmlmessage ();
} Else {
Alert ("not able to retrieve description" + request. statustext );
}
}
}
/*
* Parse HTML files
*/
Function parsehtmlmessage (){
// Obtain the returned HTML code
VaR htmlcode = request. responsetext;
// Bind HTML code
Bindtext ("elementid", htmlcode );
}
4. Data Binding
Data Binding based on different control types, you can use the following two data binding functions to bind select controls, UL unordered lists, and insert HTML code :/*
* Bind a result set
*/
Function binditems (elementid, items ){
VaR ELEM = $ (elementid );
// Determine whether the object to be bound matches the type
If (ELEM. tagname. tolowercase ()! = "Select" & ELEM. tagname. tolowercase ()! = "Ul "){
Alert ("data types do not match and cannot be bound to data ");
Return;
}
// Bind select
If (ELEM. tagname. tolowercase () = "select "){
While (ELEM. childnodes. length> 0 ){
// Clear existing data
ELEM. removechild (ELEM. childnodes [0]);
}
// Bind data
For (VAR I = 0; I <items. length; I ++ ){
VaR option = Document. createelement ("option ");
VaR DATA = items [I];
Option. value = data. childnodes [0]. firstchild. nodevalue;
Option. Text = data. childnodes [1]. firstchild. nodevalue;
ELEM. Options. Add (option );
}
} Else if (ELEM. tagname. tolowercase () = "Ul "){
// Bind the UL list
ELEM. innerhtml = "";
// Bind data
For (VAR I = 0; I <items. length; I ++ ){
VaR DATA = items [I];
VaR urladdress = data. childnodes [0]. firstchild. nodevalue;
VaR showtext = data. childnodes [1]. firstchild. nodevalue;
VaR innercode = "<li> <a href =/" "+ urladdress +"/"Title =/" "+ showtext +"/">" + showtext + "</> </LI> ";
ELEM. innerhtml + = innercode;
}
}
}
/*
* You can bind a string to HTML code.
*/
Function bindtext (elementid, value ){
VaR ELEM = $ (elementid );
// Analyze the bound object type
Switch (ELEM. tagname. tolowercase ()){
Case "Div ":
Case "span ":
Case "textarea ":
ELEM. innerhtml = value;
Break;
Case "input ":
ELEM. value = value;
Break;
Default:
Alert ("data types do not match and cannot be bound to data ");
Return;
}
Savehistory (elementid); // Save the history to implement the forward and backward buttons of the browser.
}
5. Advanced functions-implement ajax to submit form
When submitting a form through Ajax, there are two very important points: 1. You need to parse all the controls in the form and splice them into a control similar to "? Param1 = value1 & param2 = value2 ...... "And then asynchronously submit the string in the" Post "mode. send (data) to the server. 2. For file upload, I did not write a test code because I did not have this requirement. However, by reading relevant information, I can see that this function can be achieved by hiding IFRAME. The code for Asynchronously submitting a form through Ajax is as follows :/*
* Submit a form asynchronously using Ajax
*/
Function submitformbyajax (formid ){
Sendrequestbyajax ($ (formid). method, $ (formid). getattributenode ("action"). Value, encodeformdata ($ (formid), htmlcallback );
} The function used to parse the Form Control and splice it into a string is as follows :/*
* Analyze form data
* @ Param formelement form object
*/
Function encodeformdata (formelement ){
VaR whereclause = "";
VaR and = "";
For (I = 0; I <formelement. length; I ++ ){
VaR element = formelement [I];
If (element. Name! = ""){
If (element. type = 'select-one '){
Element_value = element. Options [element. selectedindex]. value;
} Else if (element. type = 'checkbox' | element. type = 'Radio '){
If (element. Checked = false ){
Break;
}
Element_value = trim (element. value );
} Else {
Element_value = trim (element. value );
}
Whereclause + = and + trim (element. Name) + '=' + element_value.replace (// &/g, "% 26 ");
And = "&"
}
}
Return whereclause;
}
6. Advanced functions-implement the browser's forward and backward buttons
After using Ajax technology, many people will find that the browser's forward and backward buttons are ineffective, greatly reducing the user experience.
The disadvantages of this technique are discussed in a wide range. After continuous attempts, the function is finally implemented. It sounds very simple, that is, it is changed through a hidden IFRAME using JavaScript.
The src attribute of IFRAME activates the forward and backward buttons of the browser. A special JavaScript function is used to update page data. The Code is as follows: var historyvalue = new array (10); // The maximum number of times a record is saved.
VaR historycount = 0;
/*
* Save historical records
* @ Param elementid ID of the region to be saved
*/
Function savehistory (elementid ){
// "Historyframe" hidden iframe id Attribute Value
VaR iframedocument = $ ("historyframe ");
If (iframedocument! = NULL ){
If (historycount = 9 ){
Historycount = 0;
} Else {
Historycount ++;
}
Historyvalue [historycount] = new array (2 );
Historyvalue [historycount] [0] = elementid;
VaR element = $ (elementid );
Historyvalue [historycount] [1] = element. innerhtml;
Iframedocument. src = "/history. jsp? "+ Historycount;
}
}
/*
* Obtain historical records
* @ Param historyindex the index number of the historical record
*/
Function gethistory (historyindex ){
If (historyindex! = Historycount ){
If (historyvalue [historyindex]) {
Historycount = historyindex;
}
VaR element = $ (historyvalue [historycount] [0]);
Element. innerhtml = historyvalue [historycount] [1];
}
} The code on the history. jsp page is very simple. Only the following code is available: <SCRIPT>
VaR url = Window. Location. href;
If (URL. indexof ('? ')>-1)
{
Parent. gethistory (URL. substr (URL. indexof ('? ') + 1 ));
Document. Write (window. Location. Search. substr (1 ));
}
</SCRIPT> at the bottom of the page, remember to write the above Code: <IFRAME id = "historyframe" name = "historyframe" src = "/history. jsp? 0 "Height =" 0px "frameborder =" no "> </iframe>
VII. Summary
I think it is best for Ajax applications to implement relevant functions based on their own needs, and avoid excessive JavaScript code as much as possible, dragging down the client browser.
Because the JavaScript code design is too flexible, if the Javascript programmer level is equivalent, it will certainly be able to develop a good JavaScript program.
Javascript programmers are not good at the same level. It is best to avoid multiple people developing a javascript program at the same time to prevent the quality of JavaScript code from decreasing. Because JavaScript debugging is very inconvenient, we recommend that you use the error console of the Firefox browser more easily.