Crossing Borders: Ajax on rails

Source: Internet
Author: User

Transfer from IBM technical website

The hype of Ajax, a technology that makes web pages more interactive, has become overwhelming. The strength of the perfect integration of Ruby on Rails and Ajax has contributed to the prosperity of the framework to a certain extent. This article aims to reveal what makes Ajax on Rails such a powerful combination.

Crossing boundariesThe first two articles in the series (see references) fully introduced streamlined. This is an auxiliary framework of rails, which effectively uses scaffolding to quickly generate a simple Ajax user interface. Unless you have been isolated from each other, you will know that AJAX is such a programming technology that uses XML, JavaScript, and web standards to create highly interactive web pages, as you can see on Google Maps and many other sites. Many readers who have read streamlined have asked me to describe how Ajax runs on Ruby on Rails. This article gives a comprehensive introduction to two simple Ajax examples, extending this idea to introduce the reason why Ruby/Ajax is so successful. In the next article in this series, I will explore the JavaScript programming language.

Ajax Definition

Ajax represents Asynchronous JavaScript + XML. Jesse James Garnett, information architect, proposed this term in 2005 to describe a technology that has survived for nearly two decades in the cracks (see references ). The use of AJAX is booming, and it continues to grow in libraries, popular websites, and literature.

Ajax redefined the basic browser usage model. The original model displays a page at a time. Ajax allows the browser to communicate with the server at the page update interval. The advantage of doing so is to bring a richer user experience, but at the cost of increasing complexity. Ajax runs like this: the Javascript client library is used to send XML between the client and the server. Ajax developers can send asynchronous requests from the client at any time. Therefore, when the server processes these requests, user interaction can continue. The following describes the Ajax request process:

About this series

In the series of articles that span borders, the author Bruce Tate put forward the idea that today's Java programmers can arm themselves well by learning other methods and languages. The programming prospects have changed since Java technology became the best choice for all development projects. Other frameworks affect the construction of Java frameworks. Concepts from other linguistics can also affect Java programming. The Python (or Ruby, smalltalk, and other languages) code you write can change the Java code writing method.

This series introduces completely different programming concepts and technologies from Java development, but these concepts and technologies can also be directly applied to Java development. In some cases, these technologies need to be integrated to take advantage of them. In other cases, the concept can be applied directly. Specific tools are not important. What is important is that other languages and frameworks can affect developers, frameworks, and even basic methods in the Java Community.

  1. An event (such as a user's mouse click or programming timer trigger) starts a JavaScript function.

  2. JavaScript Functions create a request for some pages instead of the whole page. Javascript then sends the request to the Web server over HTTP.
  3. This HTTP request calls a script on the server, such as the rails Controller method or Java Servlet.
  4. This server script creates an XML document and returns it to the server.
  5. While receiving the results, the client asynchronously creates, updates, or deletes some web pages, such as list elements,divMark or image.

All Ajax applications use a method similar to this order. For example, an application allows words in the dictionary to be saved together with their definitions. Legacy applications force you to use a new page view to edit the definition. Ajax allows in-situ editing. It replaces the definition text with an entry field and replaces the form with an updated definition.

The components of the Ajax solution are:

  • The client's JavaScript library is used to manage asynchronous requests.
  • The server-side JavaScript library is used to process incoming requests and construct an XML response.
  • The client-side JavaScript library is used to process the generated XML.
  • A library called the Document Object Model (DOM) allows you to update existing web pages.
  • Auxiliary routines are used to handle unavoidable UI and integration issues.

The event/Request/response/Replacement Model is the core model of most Ajax applications, but if you are new to Ajax, you will be surprised by the huge difference between a large number of available libraries in Ajax and those libraries. There are many Ajax frameworks in this field, and their functions are often overlapping and there is no definite winner. As far as the Java market is concerned, many libraries are available, including ECHO, dojo, DWR, Google Web Toolkit (GWT), Java Web parts, ajaxanywhere, ajaxtags, scriptaculous, and prototype. These frameworks use different methods. Some Frameworks try to hide JavaScript, such as GWT, by generating a Java library of JavaScript code. Other frameworks are designed to make JavaScript easier to use. Some are quite comprehensive, such as dom4j, while others focus only on solving a small problem. Because of the many popular new technologies, it is sometimes difficult to control the scenarios where solutions are mutually cut. The implementation of debugging tools, UI practices (such as the back button) and wise development practices is very slow. The strength of the Ajax library on the Java platform comes from its diversity. This is also the shortcoming, because diversity leads to difficult decision-making, integration concerns and complexity.

With Ruby on Rails, the development experience is significantly different, for two reasons. First, Ruby on Rails has a core web development platform: Ruby on Rails. Secondly, so far, most Ajax development experiences on rails are centered around two core frameworks: scriptaculous and prototype (see references ). The rails method uses runtime code generation and custom markup, so that you do not have to worry about complex JavaScript. It's time to practice it on your own. If you want to write code while learning this article, you need to download rails and necessary Ajax frameworks (see references ). Open your rails environment and come with me.



Back to Top

Simple Rails Applications without Ajax

To use rails and Ajax, you must create an empty project and generate a controller with two methods. One controller controls a simple page, and the other controller creates an Ajax response. Enter the following code:

rails ajax            cd ajax            script/generate controller ajax show time

The first and second lines of code generate a rails project and switch to the new directory. The third line of code generatesajaxAnd view two actions:showAndtime. Listing 1 shows the code for this controller:

Listing 1. controllers with two empty Methods

            class AjaxController < ApplicationController            def show            end            def time            end            end            

First, construct two simple views without using Ajax, and then bind these two views with Ajax. Edit the show. rhtml view in APP/views/ajax to make it similar to listing 2:

List 2. Simple View

            

The code in Listing 1 and Listing 2 does not support Ajax, but I will analyze it carefully. First, check the Controller in Listing 1. Two empty controller methods are used to process incoming HTTP requests. If you do not explicitly present a view (usingrenderMethod), rails will display the view with the same name as this method. Because the scriptaculous and prototype libraries also use HTTP, rails does not need to distinguish standard HTTP and Ajax methods.

Now focus on The View in Listing 2. Most of the code is simple HTML code, with only the second linelink_toAuxiliary routine exceptions:<%= link_to "time", :action => "time" %>.

As inCrossing boundariesAs we have seen in previous articles, Ruby uses the value of its expression to replace<%=hAnd%>. In this example,link-toThe method is an auxiliary routine for generating simple HTML links. You can view the link by executing the code. By typingscript/serverStart the server and point the browser to http: // localhost: 3000/ajax/Show. You will see the view in Figure 1:

Figure 1. Simple user interface that does not involve Ajax

In the browser, click the menu item to view the page source code (View> SourceIn FirefoxView> page source). You will see the code in listing 3:

Listing 3. view generated by show. rhtml

            

Note the link code in listing 3. This template eliminates the need for rails users to face lengthy and error-prone HTML syntaxes. (The Ajax Code also runs like this: insert JavaScript code using an auxiliary method, which is used to manage remote requests and replace html .) If you click this link, you will seetimeThe default view of the method, but I have not implemented it yet. To remedy this problem, replace the code in APP/controllers/ajax_controller.rb with the code in Listing 4.timeMethod. To keep it simple, I directly present the view from the Controller. Later, I will handle everything and present the view.

Listing 4. rendering time

            def time            render_text "The current time is #{Time.now.to_s}"            end            

Now, when you click the link, the view in Figure 2 is displayed:

Figure 2. Views that do not involve Ajax

You will soon be able to see a problem with this UI. The two views do not belong to a separate page. The application represents a single concept: click a link to display the time. To update the time repeatedly, you must click the link and back button each time. Placing the link and time on the same page may solve this problem. However, if the page becomes very large or complex, re-displaying the whole page will be a waste and complicated.



Back to Top

Add Ajax

Ajax allows you to update only one part of a Web page. The rails library handles most of your work. To add ajax to this application, perform the following four steps:

  1. Configure rails to use JavaScript.
  2. Modify the time link to submit a javascript Ajax request, instead of rendering only one HTML link.
  3. Specifies the HTML clip to be updated.
  4. Prepare a location for the updated HTML content.
  5. Construct a controller method or view to present Ajax response.

First, modify the code in APP/views/ajax/show. rhtml to make it similar to listing 5:

Listing 5. Changing the display view to use Ajax

            <%= javascript_include_tag :defaults %>            

I made some changes. First, to process the configuration, simply include the necessary JavaScript library in the view. Generally, there are more views. To avoid duplication, I include JavaScript files in a common rails component, such as the rails layout. In this example, there is only one view, so everything is simplified.

Secondly, I changed the link tag to uselink_to_remote. You will be able to see the role of this link in a moment. Note the following three parameters:

  • Link text: It is copied from a non-Ajax example.

  • :updateParameters. If you have never seen this syntax before:update => 'time_div'As a named parameter, where:updateYes Name,update_divYes. This code tells the prototype library that the results in this link will usetime_divThis name updates the HTML component.
  • Code:url => {:action => "time"}Specify the URL to be called by this link.:urlObtains values from a hash ing table. In reality, the hash ing table only has one element for the Controller action::time. Theoretically, this URL can also contain the Controller name and any optional parameters required by the Controller.

In listing 5, you can also see the emptydivRails will update it with the current time.

Load the http: // localhost: 3000/ajax/show page in the browser. Click the link to see the result in figure 3.

Figure 3. View with Ajax

To better understand the situation, please check the source code of the web page. Listing 6 shows the Code:

Listing 6. display the template results (when Ajax is enabled)

            <script src="/javascripts/prototype.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/effects.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/dragdrop.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/controls.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/application.js?1159113688" type="text/javascript"></script>            

Note the Javascript list. Rails auxiliary method (include_javascript_tags :defaults. Next, we will see a newAjax.UpdaterObject JavaScript function call, rather than an HTML link. As you expectedasynchronousIs set to true. FinallydivYou cannot see the value in the tag because the initial Page has no value.



Back to Top

Use other Ajax options

AJAX can generate powerful actions and even unexpected actions. For example, the user may not notice the updated time link.link_to_remoteOption allows you to easily apply the special effect to the entry, so that users can notice the result. Now we will apply some results. Please changelink_to_remoteAuxiliary method to make it similar to listing 7:

Listing 7. Add results

            <%= link_to_remote "time",            :update => 'time_div',            :url => {:action => "time"},            :complete => "new Effect.Highlight('time_div')" %>            

The best Ajax effect will get temporary attention for your changes, but it will not last forever. Your goal should be to notify users of the changes without interrupting their workflows. Such technologies that use yellow to weaken the emphasis, or slide the content or fade out the content to make the user's attention are not a long term.

So far, the link is the only trigger you have seen. Ajax also has many other available weapons, some of which are user-driven and others are program-driven, such as clock. It is something like an alarm clock that does not require user intervention. You can use Ajaxperiodically_call_remoteMethod: update the clock periodically. Edit the code in show. rhtml according to listing 8:

Listing 8. Call remote methods on a regular basis

            <%= javascript_include_tag :defaults %>            

Figure 4 shows the result: the clock updated every second without user intervention:

Figure 4. regular update of the clock with Ajax

Although the Code in the rails view is similar to a version without Ajax, the code behind it is quite different: This version uses JavaScript instead of HTML. You can view the code in listing 9 in the source code in the browser:

Listing 9. Source Code of periodically_call_remote

            <script src="/javascripts/prototype.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/effects.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/dragdrop.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/controls.js?1159113688" type="text/javascript"></script>            <script src="/javascripts/application.js?1159113688" type="text/javascript"></script>            

Pay attention to the situation here. You are working effectively on a higher level of abstraction, rather than using small pieces of custom JavaScript fragments. The Ruby on Rails template system makes model usage quite natural.

As mentioned earlier, I am directly rendering text from the Controller. This simplification makes it easy to start programming, but it cannot continue. The view should handle the display, and the Controller should schedule data between the view and the model. This design technique is called Model-View-controller (MVC), which makes it easier to separate changes to views or models. To make this application conform to MVC, you can make rails present the default view. As expected, this content will replacetime-divPrevious content. Please follow the steps in listing 10 to change the content in APP/controllers/ajax_controller.rbtimeMethod:

Listing 10. refactoring

            def time            @time = Time.now            end            

Change the view in APP/views/ajax/time. rhtml according to listing 11:

Listing 11. Using views to render Ajax content

            <p>The current time is <%=h @time %></p>            

Set a controller method named@timeInstance variable. Because the controller does not explicitly present anything, rails presents the time. rhtml view.This usage model is exactly the same as rendering a view without Ajax.As you can see again, rails frees developers from considering the differences between Ajax and applications that do not use Ajax. From traditional web applications to Ajax, this usage model is surprisingly similar. Due to the low cost of using Ajax, more and more Rails Applications are using Ajax.



Back to Top

Other Ajax usage in rails

Rails Ajax has a broad field of experience and profound content-I cannot use a single article or even a series of articles to summarize its profound content. I can only point out that the rails Ajax support can solve other problems. Below are some common Ajax usage in rails:

  • Submit a remote form.In addition to asynchronous submission, Ajax forms in rails are executed in the same way as traditional forms. This means thatFormsThe secondary flag allows you to specify a URL to be updated and perform visualized operations, justlink_to_remoteSame. Aslink-to-remoteExtendedlink_toThe auxiliary methods are the same, railssubmit_to_remoteExtended a railssubmitAuxiliary method.

  • Execute complex scripts.Rails developers often need to execute complex scripts, far from updating a singledivAnd the execution effect is so simple. To this end, rails provides JavaScript templates. You can use a javascript template to execute any Javascript script as the result of an Ajax request. Some common usage of these templates (called RJS templates) is to update multipledivProcess Form Verification and manage Ajax error scenarios.
  • Spelling.You must provide spelling completion services for your users based on the entries in the database. For exampleBru, I want my application to notice the "Bruce Tate" value in the database. You can use ajax to regularly check field changes and send spelling completion suggestions based on the content you type.
  • Dynamically construct complex forms.In the business field, you often need to view some completed forms before you can know which field the user should complete. For example, if a user has certain types of income or expenses, the 1040ez Tax Order is invalid. You can use ajax to update the form in this process.
  • Drag and Drop.You can use rails to quickly implement drag-and-drop support, which is much easier than most other frameworks.
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.