Главная страница
Js скрипты
Php скрипты
Html шаблоны
Книги по Web дизайну

Главная страница статей --> Хитрости при программировании php, заметки по базам данных

Ajax on Rails

Источник: realcoding.net

In a few short months, Ajax has moved from an obscure and rarely used technology to the hottest thing since sliced bread. This article introduces the incredibly easy-to-use Ajax support that is part of the Ruby on Rails web application framework. This is not a step-by-step tutorial, and I assume that you know a little bit about how to organize and construct a Rails web application. If you need a quick refresher, check out Rolling with Ruby on Rails, Part 1 and Part 2.

Just in case youve been stranded on a faraway island for most of the year, heres the history of Ajax in 60 seconds or less.

In the beginning, there was the World Wide Web. Compared with desktop applications, web applications were slow and clunky. People liked web applications anyway because they were conveniently available from anywhere, on any computer that had a browser. Then Microsoft created XMLHttpRequest in Internet Explorer 5, which let browser-side JavaScript communicate with the web server in the background without requiring the browser to display a new web page. That made it possible to develop more fluid and responsive web applications. Mozilla soon implemented XMLHttpRequest in its browsers, as did Apple (in the Safari browser) and Opera.

XMLHttpRequest must have been one of the Webs best kept secrets. Since its debut in 1998, few sites have used it at all, and most developers, if they even knew about it, never used it. Google started to change that when it released a series of high-profile web applications with sleek new UIs powered by XMLHttpRequest. The most visually impressive of these is Google Maps, which gives you the illusion of being able to drag around an infinitely sizable map in its little map window.

While Googles prominent use of XMLHttpRequest dramatically demonstrated that vastly improved UIs for web apps were possible, it was Jesse James Garretts February 18 essay that finally gave this technique a usable name: Ajax (Asynchronous JavaScript and XML). That was the tipping point. Without knowing it, we as an industry had been waiting for this, and the new Ajax name spread like wildfire. I have never seen such rapid and near universal adoption of a new technology moniker!

Traditional Web App vs. an Ajax App

Let me distill the essence of an Ajax web application by examining a use case: inserting a new item into a list.

A typical user interface displays the current list on a web page followed by an input field in which the user can type the text of a new item. When the user clicks on a Create New Item button, the app actually creates and inserts the new item into the list.

At this point, a traditional web application sends the value of the input field to the server. The server then acts upon the data (usually by updating a database) and responds by sending back a new web page that displays an updated list that now contains the new item. This uses a lot of bandwidth, because most of the new page is exactly the same as the old one. The performance of this web app degrades as the list gets longer.

In contrast, an Ajax web application sends the input field to the server in the background and updates the affected portion of the current web page in place. This dramatically increases the responsiveness of the user interface and makes it feel much more like a desktop application.

You can see this for yourself. Below are links to two different weblogs, one that uses Ajax to post comments and another that does not. Try posting some comments to each one:

Traditional Web App

Ajax Web App

Ajax is all about usability--but like any technology or technique, you can use it well or use it poorly. After showing how to use Ajax, Ill give some guidelines on when to use Ajax and when not to.

How to Use Ajax in Your Web Application

The hard way to use Ajax in your web app is to write your own custom JavaScript that directly uses the XMLHttpRequest objects API. By doing this, you have to deal with the idiosyncrasies of each browser.

An easier way is to use one of several JavaScript libraries that provide higher-level Ajax services and hide the differences between browsers. Libraries such as DWR, Prototype, Sajax, and Ajax.NET are all good choices.

The easiest way of all is to use the built-in Ajax facilities of Ruby on Rails. In fact, Rails makes Ajax so easy that for typical cases its no harder to use Ajax than it is not to!

How Rails Implements Ajax

Rails has a simple, consistent model for how it implements Ajax operations.

Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web app) or trigger an Ajax operation:

1. A trigger action occurs. This could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
2. Data associated with the trigger (a field or an entire form) is sent asynchronously to an action handler on the server via XMLHttpRequest.
3. The server-side action handler takes some action (thats why it is an action handler) based on the data, and returns an HTML fragment as its response.
4. The client-side JavaScript (created automatically by Rails) receives the HTML fragment and uses it to update a specified part of the current pages HTML, often the content of a

An Ajax request to the server can also return any arbitrary data, but Ill talk only about HTML fragments. The real beauty is how easy Rails makes it to implement all of this in your web application.

Using link_to_remote

Rails has several helper methods for implementing Ajax in your views templates. One of the simplest yet very versatile methods is link_to_remote(). Consider a simple web page that asks for the time and has a link on which the user clicks to obtain the current time. The app uses Ajax via link_to_remote() to retrieve the time and display it on the web page.

My view template (index.rhtml) looks like:

title>Ajax Demo</title>
javascript_include_tag prototype %>
h1>What time is it?</h1>
div id=time_div>
I dont have the time, but
      <%= link_to_remote( click here,
                         :update => time_div,
                         :url =>{ :action => :say_when }) %>
      and I will look it up.

There are two helper methods of interest in the above template, marked in bold. javascript_include_tag() includes the Prototype JavaScript library. All of the Rails Ajax features use this JavaScript library, which the Rails distribution helpfully includes.

The link_to_remote() call here uses its simplest form, with three parameters:

1. The text to display for the link--in this case, "click here".
2. The id of the DOM element containing content to replace with the results of executing the action--in this case, time_div.
3. The URL of the server-side action to call--in this case, an action called say_when.

Figure 1. Before clicking on the link

My controller class looks like:

class DemoController < ApplicationController
  def index

  def say_when
<p>The time is <b> + DateTime.now.to_s + </b></p>

Figure 2. After clicking on the link

The index action handler doesnt do anything except letting Rails recognize that there is an index action and causing the rendering of the index.rhtml template. The say_when action handler constructs an HTML fragment that contains the current date and time. Figures 1 and 2 show how the index page appears both before and after clicking on the "click here" link.

When the user clicks on the "click here" link, the browser constructs an XMLHttpRequest, sending it to the server with a URL that will invoke the say_when action handler, which returns an HTML response fragment containing the current time. The client-side JavaScript receives this response and uses it to replace the contents of the <div> with an id of time_div.

Its also possible to insert the response, instead of replacing the existing content:

<%= link_to_remote( click here,
update => time_div,
url => { :action => :say_when },
position => after ) %>

I added an optional parameter :position => "after", which tells Rails to insert the returned HTML fragment after the target element (time_div). The position parameter can accept the values before, after, top, and bottom. top and bottom insert inside of the target element, while before and after insert outside of the target element.

In any case, now that I added the position parameter, my "click here" link wont disappear, so I can click on it repeatedly and watch the addition of new time reports.

Figure 3. The position option inserts new content

The web page doesnt change, and neither does the URL being displayed by the browser. In a trivial example like this, there has not been much of a savings over an entire page refresh. The difference becomes more noticeable when you have a more complicated page of which you need to update only a small portion.

Похожие статьи:
- Хороший дизайн
- Создание динамических элементов страницы с помощью CSS.
- Поиск по сайту - статичный контент (Perl)
- Аспектно-ориентированная веб-разработка и PHP
- Оптимизация Apache + PHP + PostgreSQL
- Выбор ключевых слов
- Что такое Ruby on Rails 1.0?
- fror = flex + ruby on rails
- Как зашифровать HTML-код веб-страницы
- Собственная статистика поисковых слов (Яндекс, Рамблер, Google,...) на PHP
- Класс для создания меню навигации на сайте
- Drag & Drop на AJAX
- Интернет-раскрутка: с чего начинать?

Оглавление | Обсудить на форуме | Главная страница сайта | Карта сайта |