Single page interface and Ajax Mode

Source: Internet
Author: User
Go to msdn http://msdn.microsoft.com/zh-cn/magazine/cc507641.aspx :dino esposito

Code download location:Cuttingedge2008_05.exe(203 KB)Browse the code online

Directory Ajax mode influence single page interface model disadvantages of single page interface model accessible rich Internet applications Ajax mode overview unique URL mode timeout mode and development of most web applications built today mode, ajax represents a pattern change for web solution architects. It interprets web-based system behaviors based on new principles and rules, and requires new algorithms to implement them. The main principle behind Ajax is that users send pure data to the Web server and then receive more pure data. The second principle of AJAX is that users coordinate operations on their own, which skips the host browser and its single-page request/response mechanism. The third Ajax principle is that the client code uses the pure data received from the server to fully update the user interface. This topic will lay the foundation for developers who are ready to completely get rid of defensive Ajax implementations (represented as partially rendered. Partial rendering is a way to implement some Ajax functions in the web form architecture. The Ajax mode is based on a new principle that requires a new design mode. The influence of the Ajax mode on ASP. NET partial rendering is a kind of intelligent content addition, which belongs to the traditional web form re-sending model. In short, the architecture and page lifecycle of partial-rendered pages are exactly the same as those on non-Ajax pages (see Figure 1). The difference is that the listener on the client only blocks default browser operations (Form submission) and replaces it with the HTTP request guided by XMLHttpRequest (see Figure 2). This method not only saves the user's whole page refresh time, but also saves the time spent by developers in the new architecture and New Mode training. Figure 1 Traditional full-page re-sending operations(Click the image to get a larger view) Figure 2 Ajax XMLHttpRequest partial Rendering(Click the image to get a larger view) needless to say, some of them provide graphical advantages in the context of the current page. However, if your application is designed around a set of independent pages, the transition from one page to the next page still needs to be loaded on the whole page. Partial rendering is suitable for replacing the internal page sending back, for example, paging the grid, adjusting the user interface after selecting a change, or editing records in place. Because partial rendering is only a more intelligent form of page sending, it has the same architecture limitations as the web form model. For example, each browser window can have only one pending request. This restriction may not cause major problems for the current web application (submitting forms and getting new pages) model. However, as you expand your understanding of Ajax, you will naturally expect users to execute multiple activities at the same time. Depending on partial rendering, you cannot execute two asynchronous operations at the same time and complete them. Partial rendering can only execute one request operation at a time to maintain the consistency of the view State (consistency is still an indispensable component of the model ). This seriously violates the first requirement in Ajax: asynchronous. Partial rendering (out-of-band execution) can be used to implement JavaScript-driven sending back, but only one can be performed at a time. If the second operation is triggered before the previous operation is completed, the pending operation is aborted so that the new operation can continue. You can change this backward victory strategy to an advanced victory model by programming, so that the current operation remains active, the new operation will be canceled by the system. In fact, this operation can only be performed at a time. To make full use of Ajax, the single-page interface model must include all the functions in a single page, or at least most of the functions. This is called the single page interface (SPI) model. In the SPI model, all interactions between the browser and the web application can only be performed within one page. This method is an innovation for Web, but it is no stranger to Windows and desktop development. In fact, the SPI model is like a Windows application with a primary (and unique) window. In the SPI model, the home page is a combination of several visual elements that can be loaded, updated, and replaced independently (see Figure 3). In this way, you do not have to reload the entire page after each user operation. At any time, only visible elements and content related to the current stage of the application are displayed. All other content is hidden, but it is displayed as long as it is used in the application process. Figure 3 Single page elements in the page(Click the image to get a larger view) the SPI Model naturally enables many highly interactive features, including local editing, context-related user interfaces, instant user feedback prompts, and asynchronous operations. However, the SPI model not only has excellent performance or response capabilities, but also has major improvements in user experience. However, even if it has so many advantages, it should be clear that using the SPI Model to design new applications is a challenging task because there are no ready-to-use patterns and best practices. The conclusion is that there is a simple method to use Ajax, which is suitable for many companies and a variety of situations. However, the current mainstream Ajax method is not convenient. To build a pure Ajax application, you need a good user interface mini-Component Library to provide various effects and special behaviors. You need a rich and customizable Document Object Model (DOM), which uses the standard W3C dom as its basic engine, however, it allows you to define a model for your specific application. Finally, you need a server and client framework to easily and effectively develop user interfaces and source code scripts. It is better to prepare some tools for debugging and testing all of this. Microsoft and some other vendors provide some of these tools. There are many small UI component libraries available for you to choose from. In addition, there are some vendors that produce various controls used to define their own client object models. What is really helpful is the improved Ajax framework specially designed to serve as an alternative model for web forms. It is inspired by the SPI model. One of these alternative programming models is the Model View Controller (MVC) framework, which can be found in the ASP. NET 3.5 extension library. However, for the moment, it does not have much content worth learning from Ajax. Although it does not block the implementation of any Ajax function, it does not seem to have any intention to develop into an SPI model. However, time will prove everything. In the SPI model, the home page points to the HTTP endpoint of the same application. It executes remote code but does not reload the entire page. It also uses controls that generate HTML and scripts to update the user interface. These controls are very intelligent and can generate many JavaScript code they need. For example, assume that there is a form for booking flights. There may be two parameters to be searched: Time or cost. If you are more interested in cheap flights, you do not need to display the time drop-down list. If you need to take off at an accurate time, you must call up the HTML that displays the time. Obviously, you only need some JavaScript to easily implement this display/hide technique. But now, the code needs to be written by PAGE developers. Controls (such as collapsiblepanel controls) provided in ASP. NET Ajax Control Toolkit (asp.net/ajax/ajaxcontroltoolkit/samples/collapsiblepanel/collapsiblepanel.aspx) can also help with this operation. Disadvantages of the single-page interface model: although the SPI Model (and the entire Ajax model included) provides a more interactive user experience, it also raises many problems, for example, searchability, history management, accessibility, and offline support. For many years, permanent links have been used to track web pages. Search engines only need to map a set of keywords to one or more URLs to build their businesses. This model works on the premise that every state in a web application corresponds to a page and a different URL. If the SPI model is in Ajax, this assumption is no longer valid. If all (or most) occurs on the same page, there is no URL conversion to mark different States and different site content. Therefore, there is no simple method to associate content (and keywords) with a unique URL. This feature of the SPI model affects searchability and History Management (for example, the ability to use the "back" and "Forward" buttons ). Browser history may eventually become obsolete, and they are the partner of traditional static Web models. However, you must know that you are too familiar with these buttons. Simply disabling them is not a feasible method. Accessibility is another big problem for Ajax applications. Most popular screen readers face great difficulties in processing any content generated by Dom scripts. According to the design, all forms of AJAX (including partial rendering) are heavily dependent on Dom scripts. Therefore, you need to solve the problem of accessibility through other means. In section 508th of Web Content Accessibility Guidelines (wcag), we recommend that you use the script language to display content or create visual elements on the page, the alternative function text provided by it should be accessible through auxiliary technologies. To comply with this suggestion, use the <NoScript> flag. Currently, most Ajax frameworks dynamically update pages without updating static information contained in the <NoScript> tag. Accessible rich Internet applications this problem seems to be a dual problem, involving both Ajax applications and the technology behind the screen reader. On the one hand, screen readers need to understand some client events, such as onclick, keypress, and readystatechange. After identifying these events in the screen reader, you can add at least the first accessible layer to a large number of Ajax-based applications. On the other hand, if the screen reader is out of the scope of the initial page loading event in the Dom, they usually do not send any new information. However, you can use some tips to let the screen reader know that some content has changed. The most effective method is to set tabindex to-1 in the root directory of the updated DOM tree. However, this is only a small trick. An accessible solution requires a more general Ajax solution. One feasible solution is W3C's new standard known as "accessible rich Internet applications" (ARIA), which consists mainly of HTML-tagged specific reader extensions. Some popular Client Ajax libraries have begun to support some Aria functions. However, in general, this is not just about the availability of Ajax accessibility compatibility standards. It also often involves the content (TAG and script) actually generated by the server control ). What is the situation for offline applications? Many developers think that offline Ajax applications cannot be implemented because Ajax applications are still completely Internet-based. In my opinion, this statement is not completely false, but it is a bit too simple. Currently, almost all web applications (Ajax and non-Ajax) are based on the Internet or intranet. However, non-Ajax applications can indeed work offline. For example, for History Management, the magic of enabling offline navigation is completely in the browser. In traditional Web applications, each HTTP request is managed by a browser. If no connection is available (before an HTTP 404 error is thrown), the browser searches for the connection in the cache of its local page. Unlike traditional Web applications, Ajax uses XMLHttpRequest objects instead of browser engines to send HTTP requests. For Ajax applications that support offline conditions, you only need to grant the XMLHTTPRequest object the permission to access the browser cache or the ability to create and manage the cache of its own accessed pages. Some Ajax frameworks have begun to introduce this feature. But this is not easy because it involves accessing the disk from JavaScript code. Ajax mode overview the next generation of web-based applications will be directly oriented to Ajax, and more will be directly oriented to rich Internet applications (RIA ). At first, the innovative version was led by the following three categories of applications: traditional websites based on HTML, hybrid applications and fat clients built to integrate multiple systems into a web-based front-end. For the first category, partial User Interface loading (partial rendering) is a simple method to implement Ajax, which has little impact on existing code and skills. However, the concept of hybrid programs itself may not be suitable for Ajax and improved user interaction. It is just a way to collect data from various sources and put it into a unified and consistent user interface. This operation can also be performed on traditional servers. But frankly speaking, AJAX can make it simpler and more effective. From the Ajax perspective, hybrid applications require standard data serialization formats (integration), lightweight frameworks used to call remote services through scripts, and updatable Dom, there may be some rich visual controls with convenient programming models. Using ajax to build a fat client is one of the greatest challenges. A fat client can be the frontend of a distributed enterprise system or the presentation logic layer of business-line applications. It can also be an independent application made public by the IT department as a web application. These applications, whether published on the internet or restricted on the Intranet, require the richness and speed of the conventional desktop UI. Compared with Windows development, web development is regressing in terms of interactivity and responsiveness. With Ajax, you can use the tools (and environment conditions) to evolve to essentially different models. However, there is a compromise that cannot be ignored. On the one hand, millions of users and developers are used to using the old web and its historical models, offline navigation, favorites, single operations, page conversion and permanent links. On the other hand, you are using Ajax and its parallel operation mode and a single automatic User Interface update function. In this case, for user tasks, the Ajax model needs to actually restore the model, not just to use the browser's history and page navigation functions. To write code for the SPI model, a new set of design patterns are required. Figure 4Lists some of the most popular Ajax modes. As you can see, most of them focus on the user interface technology and arrangement, but you should also note that, this list does not include some popular Ajax modes and practices that have been implemented in the Microsoft Ajax client library. For example, if you use ASP. NET Ajax, you do not need Ajax stubs, cross-browser JavaScript models, or call tracking models, because all these functions are preset. Figure 4 some Ajax Modes
Mode Target
Templated Browser In this mode, we recommend that you use HTML templates that dynamically populate data retrieved from remote HTTP endpoints. In this mode, we recommend that you set your own template layer instead of dynamically generating HTML la s for data based on each request. This mode is an alternative to the HTML message mode.
Cross-origin proxy This mode is used to connect the server to an accessible and publicly available service and send data back to the client. In the client browser, Ajax applications are not allowed to connect to any URL outside the page domain. However, local agents in the same domain can easily obtain data from any location and return it to the caller.
Detection Signal Because many Ajax applications may perform a large number of operations on the client without returning information, you may need to notify the server that the specified client is still active. In this mode, it is recommended that the client application regularly upload a "Detection Signal" message to indicate that the application is still loading and is running normally in the browser.
HTML message Remote HTTP endpoints usually return the client JavaScript Object Notation (JSON) data to be integrated into the existing Dom. This task can only be completed using JavaScript. However, if the client code is particularly complex or performance issues are considered, you may want to return HTML (data and layout) from the server rather than pure data.
Micro Link Ajax is mainly used to execute a large number of activities on the same page. So how to reference external content (that is, content that will be transferred to different pages in traditional Web applications )? You need a page hyperlink or microlink. A micro-link is a reference to a tag block. It is retrieved by a server call and then inserted into the page. Micro-links can be HTTP endpoints or Javascript command objects.
On-demand Javascript This is a popular JavaScript version of the delayed loading mode, which is usually used at the data access layer. Downloading all the required JavaScript code During page initialization may affect the performance and slow down the entire process. By loading JavaScript files by request, you can make the page Load faster without affecting the function.
Page Arrangement Because most application activities occur on the same page, you need to update the page content and display the latest information as the context content changes. In this mode, we only recommend that you use Dom to add/delete or display/hide elements to reflect the transition of their States.
Regular refresh The browser regularly schedules requests to obtain the latest information and refresh the user interface.
Dialog Box This mode indicates the mode of the web version or the Windows dialog box without mode. The pop-up box consists of HTML content, which is displayed before the existing content. The display time can be very short or can be displayed until the user cancels it.
Prefetch Mode In this mode, we recommend that you predict the most likely user operations and obtain the required data in advance. To implement this model, you have to pay a certain price: after all, it is just a guess, and sometimes it may be wrong. Although it can effectively improve the perception performance, this mode may also cause performance loss if the implementation effect is poor or the ideal situation is not met due to serious server bandwidth loss.
Progress indicator This mode is used to monitor the progress of server operations. The idea is that the server operation writes its own progress to a shared location, while the client monitoring service can read the progress when the progress is refreshed.
Submission restrictions One potential drawback of AJAX is that it may generate too many server requests per unit of time. If this happens, it indicates that there are obvious scalability problems. In this mode, we recommend that you use a timer to periodically upload data to the server and local cache or queue to accumulate requests.
Timeout If you perform some heavyweight operations (such as stream or regular refresh) from the client, it is difficult to ensure that each connected client actually uses this application. In this mode, we recommend that you time out the heavy operation and resume the operation when the user makes a clear request.
Unique URL This mode allows you to assign different URLs to different parts of an application that reflect different states. This mode is usually used to support history records in Ajax applications.
Virtual workspace The server must respond to the request as soon as possible, but it may not have to return all available data due to bandwidth. In this mode, we recommend that you build a virtual user interface. Even if only a small portion of data exists on the client, all data can be available. The application downloads data as needed and caches the data locally.
You should also note that Figure 4In the list mode (generally Ajax mode), the reference mode is more than the design mode. They indicate common operation execution methods, but not all of them are design problems. In Figure 4. In the remaining part of this column, I want to perform an in-depth analysis on some of the modes. In future columns, I will return to some other important models, discuss their driving force and demonstrate some implementation methods. (For details about the Ajax mode, visit ajaxpatterns.org, a very good website .) The unique URL mode URL is the foundation of the web. Users can save the desired URL for future reference, start a new content experience according to the URL, and return the URL to the previous status. In Ajax and SPI models, applications can complete many tasks in a single URL. This will make the core pillar of Web experience a radical change, that is, the discrete state of the application is identified by different URLs. The browser will build its own URL cache when users browse. However, if Ajax is used, many operations are not passed through the browser, so they are not cached in the list of accessed URLs (in this list, the "back" and "Forward" menus can be driven ). On the other hand, the client browser does not provide a javascript code programming model that adds URLs to the list. In the existing list, the browser object model only provides the forward and backward navigation methods. The "unique URL" Mode assigns a unique and meaningful URL to each important application state. For example, if you click to edit a value on the Ajax page, the new URL will be added to the browser cache, even if the operation is performed on the same page through XMLHttpRequest. You can use the following JavaScript to change the URL without reloading the page: copy the code
window.location.hash = stateInfo;
The purpose of this Code is to add the segment prefixed with # To the URL, as shown below: copy the code
http://www.contoso.com/shopping.aspx#edit-1234
When using this mode, the URL actually changes when you start any given Ajax operation, so you can track the changes in the application status through a browser. However, the operation to be executed is far more than simply capturing URLs. If the browser is directed to a URL Based on the hash value, it first loads the main URL and then looks for the page segment with this hash name. In the Ajax context, the hash name does not point to the actual page segment, but to information specific to the application that represents the current state. For example, edit-1234 may indicate that the ID of the project you are editing is 1234. The actual format depends on you. If the browser cannot find an appropriate segment, the URL hash value is ignored. In this way, the user loads the page, but may not be in the expected application state. Another technique is required. You should capture the onload event of the page, analyze the URL, extract the hash value, and run the JavaScript code required to place the page in the desired state, as shown below: copy the code
window.onload = function() {    checkAndParseURL();} checkAndParseURL() {     var state = window.location.hash;     restorePage(state);}
A similar method is also used in the history support provided by ASP. NET 3.5 extensions. For more information, visit quickstarts.asp.net/3-5-extensions/ajax. Solutions in ASP. NET 3.5 extensions have been fully integrated into this framework. It is displayed in the form of new attributes and events added to the scriptmanager control. But in the end, it will be the specific implementation of the "unique URL" mode. In addition, it should be noted that the URL-based hash value technique is not effective for Internet Explorer, because Internet Explorer cannot identify changes in the URL hash value, unless it is an embedded frame. In fact, the behavior characteristics of all browsers in processing segment navigation are different (for details about this topic, see topics ). This difference is taken into account in solutions for ASP. NET 3.5 extensions, making it a true cross-browser technique. One of the biggest advantages of the timeout mode Ajax is the ability to implement real-time page updates. However, misuse of real-time updates may pose a serious threat to applications. Assume that a user displays an active page, which polls the server every several seconds to update some content. If the user leaves for several hours but does not close the browser. The result is that the pages are constantly sending requests, which brings a lot of (and useless) workload to the server. How can I determine whether the client session times out? Session Timeout exists on the server, while client sessions cannot be ignored in Ajax. To detect the end of a Client Session, you need to check whether there is any user activity (such as clicking or hitting) within a given period of time ). The task of monitoring keyboard and mouse activity may be very heavy; we usually adopt a timer-based method, which is not only simple but also effective. To detect the end of a session based on the timer, set the client timer to expire after a specified number of seconds (more likely in minutes), stop the ongoing task, and bring up a warning box. If the user responds to the prompt, it starts processing again as usual. Figure 5Shows some JavaScript, which describes the essence of the timeout mode. A clock is embedded in the example Page. This clock can be obtained by using the label control in updatepanel and regularly updated by the timer control, as shown below: Figure 5 implements Client Session Timeout replication code
<script type="text/javascript">    var timer = null;    function pageLoad()    {        if (timer === null)        {            timer = new Samples.TaskTimer(5000, stopTask);            timer.start();        }    }    function pageUnload()    {        if (timer != null)            timer.stop();    }        function stopTask()    {        // Stop the clock         var clock = $find("<%= Timer1.ClientID%>");        clock._stopTimer();                AskIfTheUserWantsToContinue();    }        function AskIfTheUserWantsToContinue()    {        // Ask if the user wants to continue        var answer = window.confirm(          "Is it OK to continue with the clock?");        if (answer)        {            // Restart the task              var clock = $find("<%= Timer1.ClientID%>");            clock._startTimer();                        // Restart our own timeout engine            if (timer !== null)                timer.start();            return;        }            }</script>
Copy code
protected void Timer1_Tick(object sender, EventArgs e){    Label1.Text = DateTime.Now.ToLongTimeString();}
This clock represents a heavy task and may cause Server Request overflow. The idea is to set a timer and regularly ask the user if they really want to continue running the clock. The timeout code first stops the clock and then displays the message box. After receiving a response, the clock restarts. This Code uses the $ find function to locate the ASP. NET Ajax component. In this example, it is also the client object model of the ASP. NET timer Server Control. Figure 6The running page is displayed. A dialog box is displayed asking whether you are sure to continue. Figure 6 Ask the user if they want to continue(Click the image to get a larger view)

Please send your questions and comments to Dino to the cutting@microsoft.com. Cutting@microsoft.com.

Dino espositoIs Programming ASP. NET 3.5 core references . Dino has settled in Italy and often gives speeches during industry events around the world. You can join his blog at weblogs.asp.net/despos.
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.