Just kidding, original source: http://java.sun.com/developer/technicalArticles/J2EE/AJAX/
The comparison between Chinese and English is as follows. They are all translated by me. The level is limited (78 points in the CET-6 exam). Corrections are welcome:
Asynchronous JavaScript Technology and XML (AJAX)
With Java 2 Platform, Enterprise Edition
——"Asynchronous JavaScript XML Technology and 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. such content. 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. ——Used Flickr, Anyone who knows GMail, Google, Suggest or Google Maps knows that a new class of dynamic WEB applications is taking shape. These applications look very similar to traditional desktop applications, and they do not rely on plug-ins or browser special effects. In the traditional sense, a WEB application is a set of web pages. When any content on the page changes, the entire web page must be updated. Some technologies such as JavaScript and CSS are very mature. You can use them to create dynamic web pages efficiently and run on most major browsers. This article will detail several techniques that can make your WEB applications richer and more interactive (just like desktop applications).
Introducing Asynchronous JavaScript Technology and XML (AJAX)
——AJAX introduction
Using JavaScript technology, an HTML page can asynchronously make calls to the server from which it was loaded and fetch XML documents. ML 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. ——Using JavaScript technology, the HTML page can be asynchronously called on the server that generates it. service and can get the returned XML Documented results. JavaScript then uses this XML document to update or change the Document Object Model (DOM) of this web page. The term AJAX is a new term that has emerged in recent years to describe this interaction mode.
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页面、每一次客户端接到响应都要刷新和重新渲染整个页面。The WEB application we are talking about focuses on the client using the HTML document as a template or container, and the client inserts content into this container. The principle of doing this is that whenever an event occurs on the client, the client can send it to the server. Request and use the XML data returned by the server.
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 a 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.
——Some examples of AJAX usage are as follows:
Real-time form data validation: Form data like ID numbers, serial numbers, zip codes, coupon numbers, etc. can be verified before the user submits the entire form!
Auto-complete: Some specific form data such as email, name, and city name can be automatically filled in based on the type of user.
Detailed operation: Based on client events, customers can view the detailed information of a certain product without refreshing the page.
Intelligent client interface control: services such as trees, menus, and toolbars can be provided at any time without refreshing the page.
Refresh real-time data: The page can filter dynamic data from the server and display it, such as scores, stock quotes, weather forecasts, etc.
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文档对象被更新。
3rd floor
The details of each step are as follows:
1. A client event occurs.——Client event occurs:
The keyboard event of clicking a link or form element triggers the JavaScript function validate():
size="20"
name="id"
onkeyup="validate();">
2. A XMLHttpRequest object is created and configured. - An XMLHttpRequest object is created and configured:
var req;
function validate() {
var idField = document.getElementById("idField");
var url = "validate?id=" escape(idField.value);
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");——Create XMLHttpRequest object
req.open("GET", url, true);——Call the open method of the XMLHttpRequest object, url is the requested server component path, true means that the call is asynchronous,
If it is set to asynchronous, there must be a callback function as follows:
req.onreadystatechange = callback;
req.send(null);
}
3. The XMLHttpRequest object makes a call.——The XMLHttpRequest object makes a request:
Issue a request when req.send(null) is executed.
If it is a GET request, the content can be empty and parameters can be appended to the url.
If it is a POST request, then a Content-Type header needs to be set as follows:
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("id=" escape(idTextField.value));
If you use JavaScript to generate form element values, you must ensure that the value encoding is correct. JavaScript has an escape() function to ensure correct encoding and to correctly ignore specific characters.
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 generates an XML document as a response. More complex situations may use DOM, XSLT, etc.
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
Developers must know two things: first: Content-Type must be set to text/xml; second: Cache-Control must be set to no-cache.
Fourth Floor
up
5th floor
6. The XMLHttpRequest object calls the callback() function and processes the result.
——The XMLHttpRequest object calls the callback() function and processes the result.
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, signing the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction.
——When the preparation status of the XMLHttpRequest object changes, the callback() method is called. We assume that the request for ValidateServlet has been completed, the preparation status is 4, indicating that the XMLHttpRequest call has been completed, and the HTTP status code is 200, indicating that the HTTP interaction has been completed. success.
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的手段。You can use req.responseText to access the string representation of the returned XML document, as follows:
valid
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:
- The above example is a simple XML fragment, actual applications may include more:
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.
- The parseMessages() method processes the XML document returned from the server. This method uses the value of the message element to call the setMessage() method to change the HTML DOM.
6th floor
Awesome. admire. . . Thank you, host
7th floor
Not bad! Very well translated! The host speaks English very well! Level 6... Hee hee...
8th floor
7. The HTML DOM is updated.——The HTML document object is updated.
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属性、如下所示: