This is an ajax tutorial in China.
This tutorial is available everywhere. I will focus on a framework I have built myself.
Features:
Supports Form-based non-transient submission (the method is a bit stupid)
Supports the MVC framework.
Multi-thread concurrent requests (to support threads in languages)
Dynamic file loading, only useful! Handles the problem of bloated JS files in the Ajax framework.
Use the full div + css layout of no table
A. Get the XMLHTTPRequest object, which can be found everywhere on the Internet, not to mention:
Function newXMLHttpRequest (){
Var xmlreq = false;
If (window. XMLHttpRequest ){
Xmlreq = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
Try {
Xmlreq = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e1 ){
Try {
Xmlreq = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e2 ){
}
}
}
Return xmlreq;
}
Here we provide a general method to support multiple browsers.
B. Submit an asynchronous request
// Here we use Bcandy as the method name to thank someone who is very important to me and she has been supporting me.
Function Bcandy (Tid, url, parm, js ){
If (url = ""){
Return;
}
// This is a prompt box for loading information, or not!
Document. getElementById ("load"). style. visibility = "visible ";
// Load the JS file of the corresponding page
If (js! = Null ){
// Load the JS File
LoadJS (js );
}
// Obtain an XMLHttpRequest instance
Var req = newXMLHttpRequest ();
// Set the handle function used to receive callback notifications from the request object
Var handlerFunction = getReadyStateHandler (req, Tid );
Req. onreadystatechange = handlerFunction;
// The third parameter indicates that the request is asynchronous.
Req. open ("POST", url, true );
// Indicates that the request body contains form data
Req. setRequestHeader ("Content-Type ",
"Application/x-www-form-urlencoded ");
// Sending Parameters
Req. send (parm );
}
Function getReadyStateHandler (req, Tid ){
// Returns an anonymous function that listens to the XMLHttpRequest instance.
Return function (){
// If the request status is "complete"
If (req. readyState = 4 ){
// The server response is successfully received.
If (req. status = 200 ){
// The following sentence is important. The content of the returned information is displayed and can be modified. Other Processing
Document. getElementById (Tid). innerHTML = req. responseText;
Document. getElementById (Tid). style. visibility = "visible ";
// This statement is used to hide or hide the loading prompt box.
Document. getElementById ("load"). style. visibility = "hidden ";
} Else {
// An HTTP Error occurs.
Document. getElementById ("load"). style. visibility = "hidden ";
Alert ("HTTP error:" + req. status );
}
}
}
}
// Dynamically load JS files
Function LoadJS (file ){
Var head = document. getElementsByTagName ('head'). item (0 );
Var script = document. createElement ('script ');
Script. src = file;
Script. type = "text/javascript ";
Head. appendChild (script );
}
This is the basic framework, because the request is used. responseText; therefore, you can directly request a page jsp, servlet, but special processing is required for requests using the Struts framework, because Form does not support asynchronous requests. We recommend that you do not add tags on these pages, just like the asxm file in. net! When using the Struts framework, note that the Mapping object can return null directly, because we will talk about concurrent multithreading below. To solve this problem.
In general, it seems like building blocks. This facilitates File Modification and expansion without affecting each other, and achieves code and tag separation. During the traditional page revision, you do not need to rewrite all the code. You only need to modify a small part to perfectly implement the non-flash refreshing pleasure brought by Ajax.
The above code has been tested in IE and FireFox!
First, create a data table menu
MId menu primary key
Name menu name
Url menu Link
Father low-level menu ID
Whether sub is the underlying menu (used to determine whether sub can be expanded)
Target menu Link target (as the display id when opened in ajax Mode)
Pa menu parameters (this is used to open the menu in ajax Mode)
Create a menu object class
Class Menu {
Private int mId;
Private String name;
... // Other members
Public getMid (){
Return mId;
}
Public setMid (int mId ){
This. mId = mId;
}
... // Get set Method for other members,
}
The other is the operation class.
Class MenuOpt (){
Public Vector getMenus (int father ){
Vector vector = new Vector ();
// Obtain all the menus whose parent menu ID is father.
// And encapsulate it in an object of the Vector ..
Return vector;
}
}
The second is the general jsp file. But do not include tags as you have mentioned before!
Menu. jsp:
% @ Page contentType = "text/html; charset = GB2312" %>
% @ Taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
Jsp: useBean id = "menu" scope = "page" class = "ycoe. basic. MenuOpt"/>
Jsp: setProperty name = "menu" property = "father" value = "$ {param. father}"/>
Div>
C: forEach var = "m" items = "$ {menu. vector}" varStatus = "c">
C: choose>
C: when test = "$ {m. sub eq 'y'}">
Div onClick = "showmenu('{}m.mid}', '{}m.url}', '{}m.tar get} ', 'Father =$ {m. mid}')">
Img src = "pic/menu0.gif" id = "img $ {m. mid}" alt = "" style = "cursor: hand;">
A href = "#" class = "text1" >$ {m. name}
/Div>
Div style = "display: none;" id = "tr $ {m. mid}">
Div style = "padding-left: 12pt" id = "$ {m. mid}">
/Div>
/C: when>
C: otherwise>
Div onclick = "openmenu('{}m.url}', '{}m.tar get} ',' $ {m. pa} ');">
Img src = "pic/menu1.gif" id = "img $ {m. mid}" alt = "">
A href = "#" class = "text1" >$ {m. name}
/Div>
Menu. js:
// OperMenu (open the drop-down menu ID, open address, link to open the target, parameters ).
// This is the method used in menu. jsp
Function showMenu (id, url, target, param ){
Var trObj = document. getElementById ("tr" + id );
Var tdObj = document. getElementById (id );
// Try {
If (document. getElementById ("tr" + id). style. display = "none "){
// Display menu
If (tdObj. innerHTML = null | tdObj. innerHTML = ""){
// Extract data
Document. getElementById ("tr" + id). style. display = "";
Document. getElementById ("img" + id). src = "pic/menu2.gif"
Bcandy (id, "page/menu. jsp", param ,"");
OpenMenu (url, target, param );
} Else {
// If there is content in it, it is displayed directly
Document. getElementById ("tr" + id). style. display = "";
Document. getElementById ("img" + id). src = "pic/menu2.gif"
OpenMenu (url, target, param );
}
// Bcandy (target, url, param, ""); // open the menu Link
} Else {
// Hide the menu
Document. getElementById ("tr" + id). style. display = "none ";
Document. getElementById ("img" + id). src = "pic/menu0.gif"
}
//} Catch (e ){}
}
// Open the menu
Function openMenu (url, target, param ){
// Do not write it here. There are several implementation methods. We recommend using ajax!
}
Finally, the page is displayed:
% @ Page contentType = "text/html; charset = GB2312" %>
Meta http-equiv = Content-Type content = "text/html; charset = gb2312">
Style>
. Text1: hover {border: 1px #999999 solid; background-color: # CCCCCC; height: 12px ;}
. Text1 {border: 1px # FFFFFF solid; height: 12px ;}
Function ini (){
Bcandy ("0", "menu. jsp", "id = 0 & father = 0", "menu. js ");
}
Body onload = "ini ();">
Div id = "load" style = "z-index: 1; color: # FF0000; visibility: hidden; filter: Alpha (opacity = 85); background-color: # FFFFFF; left: 48%; top: 48%; BORDER-RIGHT: #000000 1px solid; PADDING-RIGHT: 12px; BORDER-TOP: #000000 1px solid; PADDING-LEFT: 12px; PADDING-BOTTOM: 12px; BORDER-LEFT: #000000 1px solid; LINE-HEIGHT: 22px; PADDING-TOP: 12px; BORDER-BOTTOM: #000000 1px solid; POSITION: absolute; ">
Img src = 'pic/loop.gif 'alt = "">
Processing Data. Please wait...
Br>
Div id = "0" align = "center">
We can see that at any level, there is nothing different from the traditional one. Only the jsp part removes the file header (in fact, it does not remove the file header). In addition, we can also see that, A page has been divided into several parts. As I mentioned earlier, it is a modular structure (this is a structure proposed by the author when I saw a. net Framework Structure on the Internet. I think it is good and I applied it to JSP ).
I have made some reservations for some details. Please understand. However, the general framework is tested by IE and FireFox. I think about some functional extensions.
Principle: Page recursion is actually applied! Just like a general recursive method, but it is only used on the page.
Div id = "tr $ {m. id}">
Loop to display the objects encapsulated into the vector one by one
For {
If (if it is the top menu sub = N ){
Div id = "t $ {m. id}" onClick = "ShowMenu ($ {m. father...})">
Show menu content
Div style = "display: none" id = "td $ {m. id...}">
} Else {
Div onClick = "OpenMenu ($ {m. id})"> display menu content
}
}
The showMenu (father, id...) method calls this page again after obtaining data from the server based on the passed-in father. In this case, the page content is displayed in the new ID. In this way, it looks like the tree menu in MSDN.
Advantage: Multi-Level menus are obtained multiple times, which speeds up the response. ajax requests are also applied, making the page flickering invisible and highly friendly. In addition, code can be added to JS so that users do not need to obtain server data every time they click. Instead, they can first determine whether there is any content and no more data... At the same time, menus and pages are synchronized. You can open the page at the corresponding place for each level menu opened. Similarly, operMenu () can also be ajax.
Effect can be on the http://www.start.com/Look: