開玩笑、原文出處:http://java.sun.com/developer/technicalArticles/J2EE/AJAX/
中英文對照如下、全是我自己譯的、水平有限(6級考78分)、歡迎指正:
Asynchronous JavaScript Technology and XML (AJAX)
With Java 2 Platform, Enterprise Edition
——《異步JavaScript+XML技術與J2EE》
By Greg Murray, June 9, 2005
Anyone who has used Flickr, GMail, Google Suggest, or Google Maps will realize that a new breed of dynamic web applications is emerging. These applications look and act very similar to traditional desktop applications without relying on plug-ins or browser-specific features. Web applications have traditionally been a set of HTML pages that must be reloaded to change any portion of the content. Technologies such as JavaScript programming language and cascading style sheets (CSS) have matured to the point where they can be used effectively to create very dynamic web applications that will work on all of the major browsers. This article will detail several techniques that you can use today to enable your web applications to be more rich and interactive like desktop applications. ——使用過Flickr、GMail,、Google、Suggest或Google地圖的人都知道一種全新的動態WEB應用正在成型、這些應用看上去和傳統桌面應用非常相似、他們不依賴於插件或者浏覽器特效。傳統意義上的WEB應用就是一組網頁、當頁面上有任何一點內容有所變化的時候必須更新整個網頁。一些技術比如JavaScript和CSS已經非常成熟、你可以使用他們高效的創建動態網頁、並可以跑在大多數主流浏覽器上。本文將細述數種可以使你的WEB應用更豐富更具交互性(就象桌面應用一樣)的技術。
Introducing Asynchronous JavaScript Technology and XML (AJAX)
——AJAX介紹
Using JavaScript technology, an HTML page can asynchronously make calls to the server from which it was loaded and fetch XML documents. The XML documents may then be used by the JavaScript technology to update or modify the Document Object Model (DOM) of the HTML page. The term Asynchronous JavaScript Technology and XML (AJAX) has emerged recently to describe this interaction model. ——使用JavaScript技術、HTML網頁可以異步調用生成它的服務器上的服務並可以獲取返回的XML文檔形式的結果。JavaScript再使用這個XML文檔更新或改動本網頁的文檔對象模型(DOM)、名詞AJAX就是近年來出現的用與描述這種交互模式的新名詞。
AJAX is not new. These techniques have been available to developers targeting Internet Explorer on the Windows platform for many years. Until recently, the technology was known as web remoting or remote scripting. Web developers have also used a combination of plug-ins, Java applets, and hidden frames to emulate this interaction model for some time. What has changed recently is that the inclusion of support for the XMLHttpRequest object has became ubiquitous in the mainstream browsers across all platforms. The real magic is the result of the JavaScript technologys XMLHttpRequest object. Although this object is not specified in the formal JavaScript technology specification, all of todays mainstream browsers support it. The subtle differences with the JavaScript technology and CSS support among current generation browsers such as Firefox, Internet Explorer, and Safari are manageable. If you are required to support older browsers, AJAX may not be the answer for you. ——AJAX並不是新事物、數年前使用微軟IE浏覽器的開發者們就在使用它、直到最近、這項技術被冠以遠程腳本而更出名了。以前WEB開發者使用插件、applets或者隱藏框架來仿效這種交互模式。但是現在由於XMLHttpRequest對象技術已經在各大平台的主流浏覽器上普及、所以這種模仿的情況越來越少了。真正神奇的事情在於JavaScript和XMLHttpRequest對象技術的結合、盡管XMLHttpRequest對象技術並不屬於JavaScript標准規范、但是現代的主流浏覽器都支持、在Firefox、IE、 Safari這些浏覽器對JavaScript和CSS的執行有微小不同、但這些不同之處很容易理解和處理。如果你一定要兼容老一代浏覽器那還是不要用AJAX了。
//////////////////////////////////////////////////////////////////////////////////////////
1樓
BS 婁豬
2樓
What makes AJAX-based clients unique is that the client contains page-specific control logic embedded as JavaScript technology. The page interacts with the JavaScript technology based on events such as the document being loaded, a mouse click, focus changes, or even a timer. AJAX interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in bite-size pieces of data as needed rather than reloading the whole page every time a change needs to be displayed. AJAX will require a different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event resulting in a call to the server. The clients would then refresh and re-render the complete HTML page for each response. Rich web applications focus on a client fetching an HTML document that acts as a template or container into which to inject content, based on client events using XML data retrieved from a server-side component.——是什麼使得基於AJAX的客戶端如此獨特?那就是客戶端所嵌入的頁面特定的控制邏輯、這些控制邏輯以JavaScript代碼的形式存在。頁面與JavaScript的交互建立在事件的基礎上(比如文檔加載事件、鼠標點擊事件、焦點變化事件、甚至一個時鐘事件)。AJAX清楚的將表示邏輯和數據分離開來、一個HTML網頁能夠在需要的時候獲取以比特為單位的數據片段!這不同於以前的有一點變化就必須刷新整個頁面的做法。同時AJAX也需要一種完全不同的服務端架構來支持這種交互模式。以前的傳統服務端WEB應用專注於為每一個客戶端的每一次請求生成HTML頁面、每一次客戶端接到響應都要刷新和重新渲染整個頁面。而我們所談的WEB應用專注於客戶端把HTML文檔當作模版或容器、客戶端向這個容器中插入內容、作到這些的原理就是每當客戶端發生事件、客戶端都可以向服務端發出請求並使用服務端返回的XML數據。
Some uses for AJAX interactions are the following:
Real-Time Form Data Validation: Form data such as user IDs, serial numbers, postal codes, or even special coupon codes that require server-side validation can be validated in a form before the user submits a form.
Autocompletion: A specific portion of form data such as an email address, name, or city name may be autocompleted as the user types.
Master Details Operations: Based on a client event, an HTML page can fetch more detailed information on data such as a product listing that enables the client to view the individual product information without refreshing the page.
Sophisticated User Interface Controls: Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes.
Refreshing Data on the Page: HTML pages may poll data from a server for up-to-date data such as scores, stock quotes, weather, or application-specific data.
——一些AJAX的使用例子如下:
實時的表單數據驗證:象ID號、序列號、郵政編碼、優惠卷號碼這樣的表單數據可以在用戶提交整個表單之前就得到驗證!
自動補全:一些特定表單數據比如email、姓名、城市名可以根據用戶的類型自動填寫。
細節操作:基於客戶端事件、客戶可以不刷新頁面就可以查看某一種產品的細節信息。
智能客戶端接口控制:諸如樹、菜單、工具條都可以在不刷新頁面的情況下隨時提供服務。
刷新實時數據:頁面可以從服務端篩選動態數據並顯示、諸如:比分、股票報價、天氣預報等。
This list is not all-inclusive, but it shows that AJAX interactions allow web applications to do much more than they have done in the past. Although many of these benefits are noteworthy, this approach has some drawbacks as well:
Complexity: Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic to generate the XML content needed by the client HTML pages. HTML page developers must have JavaScript technology skills. Creating AJAX-enabled applications will become easier as new frameworks are created and existing frameworks evolve to support the interaction model.
Standardization of the XMLHttpRequest Object: The XMLHttpRequest object is not yet part of the JavaScript technology specification, which means that the behavior may vary depending on the client.
JavaScript Technology Implementations: AJAX interactions depend heavily on JavaScript technology, which has subtle differences depending on the client. See QuirksMode.org for more details on browser-specific differences.
Debugging: AJAX applications are also difficult to debug because the processing logic is embedded both in the client and on the server.
Viewable Source: The client-side JavaScript technology may be viewed simply by selecting View Source from an AJAX-enabled HTML page. A poorly designed AJAX-based application could open itself up to hackers or plagiarism.
Frameworks and patterns for AJAX technology are likely to emerge as developers gain more experience writing applications that use the AJAX interaction model. It is still early to focus on a one-size-fits-all framework for AJAX interactions. This article and the associated solutions focus on how AJAX interactions can be supported today by existing Java 2 Platform, Enterprise Edition (J2EE) technologies such as servlets, JavaServer Pages (JSP) software, JavaServer Faces applications, and the Java Standard Tag Libraries (JSTL).
——這些用處並不全、但是它們說明了AJAX交互使得WEB應用可以作到大量以前無法作到的事情。這些事情可能並不多麼引人注目、而且還有一些缺陷:
復雜性:服務端開發者必須掌握XML、頁面開發者必須掌握JavaScript技術。
XMLHttpRequest對象的標准化:XMLHttpRequest對象仍不是JavaScript標准規范。
JavaScript技術實現:AJAX嚴重依賴與JavaScript技術。可參考QuirksMode.org。
Debugging:AJAX難於調試。
查看原文件:使用這種方法可以容易的看到JavaScript源碼、給黑客、剽竊者以可乘之機。
AJAX技術框架和模式還在探索和經驗形成階段、固化形成一個真正的框架還為時過早。本文只是探討如何使用J2EE技術來支持AJAX交互。
The Anatomy of an AJAX Interaction
Now that we have discussed what AJAX is and what some higher-level issues are, lets put all the pieces together and show an AJAX- enabled J2EE application.
Lets consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the AJAX interaction that will provide the validation logic
——AJAX交互剖析:來看一個AJAX使能的J2EE應用:名為ValidateServlet的Servlet驗證表單數據、但是要求不能對整個頁面刷新。步驟如下:
1、A client event occurs. ——客戶端事件發生。
2、An XMLHttpRequest object is created and configured. ——一個XMLHttpRequest對象被創建並配置。
3、The XMLHttpRequest object makes a call. ——XMLHttpRequest對象發出請求。
4、The request is processed by the ValidateServlet. ——請求被ValidateServlet處理。
5、The ValidateServlet returns an XML document containing the result. ——ValidateServlet返回一個包含結果的XML文檔。
6、The XMLHttpRequest object calls the callback() function and processes the result. ——XMLHttpRequest對象調用callback()函數並處理結果。
7、The HTML DOM is updated.——HTML文檔對象被更新。
3樓
各個步驟細節如下:
1. A client event occurs.——客戶端事件發生:
點擊鏈接或表單元素的鍵盤事件引發JavaScript函數validate():
<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validate();">
2. A XMLHttpRequest object is created and configured.——一個XMLHttpRequest對象被創建並配置:
var req;
function validate() {
var idField = document.getElementById("idField");
var url = "validate?id=" + escape(idField.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");——創建XMLHttpRequest對象
}
req.open("GET", url, true);——調用XMLHttpRequest對象的open方法、url為所請求的服務端組件路徑、true表示這個調用是異步的、
如果設置為異步就必須還要有一個callback函數如下:
req.onreadystatechange = callback;
req.send(null);
}
3. The XMLHttpRequest object makes a call.——XMLHttpRequest對象發出請求:
執行到req.send(null)的時候發出請求。
如果是GET請求那麼內容可以為空、在url附加參數。
如果是POST請求那麼就需要一個Content-Type頭的設置如下:
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("id=" + escape(idTextField.value));
如果用JavaScript產生表單元素值、必須確保值編碼的正確、JavaScript有一個escape()函數用於保障正確的編碼、並把特定字符正確的忽略掉。
4. The request is processed by the ValidateServlet.——請求被ValidateServlet所處理:
servlet處理XMLHttpRequest就和處理其他HTTP請求一樣:
public class ValidateServlet extends HttpServlet {
private ServletContext context;
private HashMap users = new HashMap();
public void init(ServletConfig config) throws ServletException {
this.context = config.getServletContext();
users.put("greg","account data");
users.put("duke","account data");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !users.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("valid");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
}
}
}
5. The ValidateServlet returns an XML document containing the results.——ValidateServlet返回一個包含結果的XML文檔。
ValidateServlet生成一個XML文檔作為響應、更復雜的情況可能用到DOM、XSLT等。
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
開發者必須了解兩件事:第一:Content-Type必須設置為text/xml;第二:Cache-Control必須設置為no-cache。
4樓
up
5樓
6. The XMLHttpRequest object calls the callback() function and processes the result.
——XMLHttpRequest對象調用callback()函數並處理結果。
The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction.
——XMLHttpRequest對象的准備狀態有所變化的時候則調用callback()方法、我們假定已經請求完畢ValidateServlet、准備狀態為4、表示XMLHttpRequest調用已經完成、HTTP狀態碼為200、表示HTTP交互已經成功。
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
// update the HTML DOM based on whether or not message is valid
}
}
}
Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded.
——浏覽器維護著一個文檔的對象表示模型、既:DOM。網頁中的JavaScript方法可以訪問這個模型、並且可以在頁面已經全部加載完成後再次改變這個模型。
Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now lets look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.
——使用JavaScript代碼:req.responseXML可以得到服務端返回的XML文檔、req為XMLHttpRequest對象、DOM為JavaScript提供了一種搜索文檔內容以及根據搜索結果改變網頁DOM的手段。可以使用req.responseText來訪問返回的XML文檔的字符串表示、如下所示:
<message>
valid
</message>
This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user:
——上面的例子是一個簡單的XML片段、實際應用可能包含更多:
function parseMessage() {
var message = req.responseXML.getElementsByTagName("message")[0];
setMessage(message.childNodes[0].nodeValue);
}
The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
——parseMessages()方法處理從服務端返回的XML文檔、該方法使用message元素的值去調用setMessage()方法來改變HTML DOM。
6樓
厲害。佩服。。。謝謝樓主
7樓
不錯不錯!翻譯得很好!樓主得英語很好啊!6級啊…………嘻嘻……
8樓
7. The HTML DOM is updated.——HTML文檔對象被更新。
JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById("userIdMessage"), where "userIdMessage" is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the elements attributes; modify the elements style properties; or add, remove, or modify child elements.
One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.
——JavaScript可以獲得HTML DOM中任何元素(對象)的引用、推薦使用document.getElementById("userIdMessage")方法來獲取。userIdMessage就是網頁上任意元素的ID屬性、有了元素(對象)的引用、JavaScript就可以改變這個元素的屬性以及這個元素的樣式屬性、還可以增加刪除或改變這個元素的子元素。通用的方法是設置innerHTML屬性、如下所示:
<script type="text/javascript">
function setMessage(message) {
var userMessageElement = document.getElementById("userIdMessage");
userMessageElement.innerHTML = "<font color=\"red\">" + message + " </font>";
}
</script>
<body>
<div id="userIdMessage"></div>
</body>
The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as <image> or <iframe>, the content specified by those elements is fetched and rendered as well.
——innerHTML屬性被改變以後網頁可以立即體現出變化、如果innerHTML屬性內部包含象<image>、<iframe>這樣的元素、那麼其所指定的資源內容一樣被浏覽器解析顯示。
The main drawback with this approach is that HTML elements are hardcoded as strings in the JavaScript technology code. Hardcoding HTML markup inside JavaScript technology code is not a good practice because it makes the code difficult to read, maintain, and modify. Consider using the JavaScript technology DOM APIs to create or modify HTML elements within JavaScript technology code. Intermixing presentation with JavaScript technology code as strings will make a page difficult to read and edit.
Another means of modifying the HTML DOM is to dynamically create new elements and append them as children to a target element as in the following example.
——這種方法最大的缺點是在JavaScript代碼裡面難於以字符串形式書寫HTML、內嵌於JavaScript中的HTML也難以看懂、維護和更改。另外的改變HTML DOM的方法是動態創建新元素然後將其作為子元素插入目標元素下、如下所示:
<script type="text/javascript">
function setMessage(message) {
var userMessageElement = document.getElementById("userIdMessage");
var userIdMessageFont = document.getElementById("userIdMessageFont");
var messageElement = document.createTextNode(message);
if (userMessageElement.childNodes[0]) {
// update the elements
userIdMessageFont.replaceChild(messageElement, userIdMessageFont.childNodes[0]);
} else {
// create the new elements
var fontElement = document.createTextNode("font");
fontElement.setAtribute("id", "userIdMessageFont");
fontElement.setAtribute("color", "red");
userMessageElement.appendChild(fontElement);
fontElement.appendChild(messageElement);
}
}
</script>
<body>
<div id="userIdMessage"></div>
</body>
——全文完、累死了。
9樓
精簡版:
客戶端所嵌入的頁面特定的控制邏輯以JavaScript代碼的形式存在。頁面與JavaScript的交互建立在事件的基礎上(比如文檔加載事件、鼠標點擊事件、焦點變化事件、甚至一個時鐘事件)。AJAX清楚的將表示邏輯和數據分離開來、一個HTML網頁能夠在需要的時候獲取以比特為單位的數據片段!這不同於以前的有一點變化就必須刷新整個頁面的做法。同時AJAX也需要一種完全不同的服務端架構來支持這種交互模式。以前的傳統服務端WEB應用專注於為每一個客戶端的每一次請求生成HTML頁面、每一次客戶端接到響應都要刷新和重新渲染整個頁面。而我們所談的WEB應用專注於客戶端把HTML文檔當作模版或容器、客戶端向其中插入內容、其原理就是每當客戶端發生事件、客戶端都可以向服務端發出請求並使用服務端返回的XML數據。
名為ValidateServlet的Servlet驗證表單數據、但是要求不能對整個頁面刷新。步驟如下:
1. A client event occurs.——客戶端事件發生:
點擊鏈接或表單元素的鍵盤事件引發JavaScript函數validate():
<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validate();">
2. A XMLHttpRequest object is created and configured.——一個XMLHttpRequest對象被創建並配置:
var req;
function validate() {
var idField = document.getElementById("idField");
var url = "validate?id=" + escape(idField.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");——創建XMLHttpRequest對象
}
req.open("GET", url, true);——調用XMLHttpRequest對象的open方法、url為所請求的服務端組件路徑、true表示這個調用是異步的、
如果設置為異步就必須還要有一個callback函數如下:
req.onreadystatechange = callback;
req.send(null);
}
3. The XMLHttpRequest object makes a call.——XMLHttpRequest對象發出請求:
如果是GET請求那麼內容可以為空、在url附加參數。
如果是POST請求那麼就需要一個Content-Type頭的設置如下:
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("id=" + escape(idTextField.value));
如果用JavaScript產生表單元素值、必須確保值編碼的正確、JavaScript有一個escape()函數用於保障正確的編碼、並把特定字符正確的忽略掉。
4. The request is processed by the ValidateServlet.——請求被ValidateServlet所處理:
servlet處理XMLHttpRequest就和處理其他HTTP請求一樣:
public class ValidateServlet extends HttpServlet {
private ServletContext context;
private HashMap users = new HashMap();
public void init(ServletConfig config) throws ServletException {
this.context = config.getServletContext();
users.put("greg","account data");
users.put("duke","account data");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !users.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("valid");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
}
}
}
5. The ValidateServlet returns an XML document containing the results.——ValidateServlet返回一個包含結果的XML文檔。
ValidateServlet生成一個XML文檔作為響應、更復雜的情況可能用到DOM、XSLT等。
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
開發者必須了解兩件事:第一:Content-Type必須設置為text/xml;第二:Cache-Control必須設置為no-cache。
6. The XMLHttpRequest object calls the callback() function and processes the result.
——XMLHttpRequest對象調用callback()函數並處理結果。
XMLHttpRequest對象的准備狀態有所變化的時候則調用callback()方法、我們假定已經請求完畢ValidateServlet、准備狀態為4、表示XMLHttpRequest調用已經完成、HTTP狀態碼為200、表示HTTP交互已經成功。
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
// update the HTML DOM based on whether or not message is valid
}
}
}
浏覽器維護著一個文檔的對象表示模型、既:DOM。網頁中的JavaScript方法可以訪問這個模型、並且可以在頁面已經全部加載完成後再次改變這個模型。
使用JavaScript代碼:req.responseXML可以得到服務端返回的XML文檔、req為XMLHttpRequest對象、DOM為JavaScript提供了一種搜索文檔內容以及根據搜索結果改變網頁DOM的手段。可以使用req.responseText來訪問返回的XML文檔的字符串表示、如下所示:
<message>
valid
</message>
上面的例子是一個簡單的XML片段、實際應用可能包含更多:
function parseMessage() {
var message = req.responseXML.getElementsByTagName("message")[0];
setMessage(message.childNodes[0].nodeValue);
}
parseMessages()方法處理從服務端返回的XML文檔、該方法使用message元素的值去調用setMessage()方法來改變HTML DOM。
7. The HTML DOM is updated.——HTML文檔對象被更新。
JavaScript可以獲得HTML DOM中任何元素(對象)的引用、推薦使用document.getElementById("userIdMessage")方法來獲取。userIdMessage就是網頁上任意元素的ID屬性、有了元素(對象)的引用、JavaScript就可以改變這個元素的屬性以及這個元素的樣式屬性、還可以增加刪除或改變這個元素的子元素。通用的方法是設置innerHTML屬性、如下所示:
<script type="text/javascript">
function setMessage(message) {
var userMessageElement = document.getElementById("userIdMessage");
userMessageElement.innerHTML = "<font color=\"red\">" + message + " </font>";
}
</script>
<body>
<div id="userIdMessage"></div>
</body>
innerHTML屬性被改變以後網頁可以立即體現出變化、如果innerHTML屬性內部包含象<image>、<iframe>這樣的元素、那麼其所指定的資源內容一樣被浏覽器解析顯示。
這種方法最大的缺點是在JavaScript代碼裡面難於以字符串形式書寫HTML、內嵌於JavaScript中的HTML也難以看懂、維護和更改。另外的改變HTML DOM的方法是動態創建新元素然後將其作為子元素插入目標元素下、如下所示:
<script type="text/javascript">
function setMessage(message) {
var userMessageElement = document.getElementById("userIdMessage");
var userIdMessageFont = document.getElementById("userIdMessageFont");
var messageElement = document.createTextNode(message);
if (userMessageElement.childNodes[0]) {
// update the elements
userIdMessageFont.replaceChild(messageElement, userIdMessageFont.childNodes[0]);
} else {
// create the new elements
var fontElement = document.createTextNode("font");
fontElement.setAtribute("id", "userIdMessageFont");
fontElement.setAtribute("color", "red");
userMessageElement.appendChild(fontElement);
fontElement.appendChild(messageElement);
}
}
</script>
<body>
<div id="userIdMessage"></div>
</body>