`
lzj520
  • 浏览: 215858 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

(转)Ajax on Rails(onlamp.com)

    博客分类:
  • Ajax
阅读更多

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 Railsweb 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 you've been stranded on a faraway island for most of the year, here's 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 Web's 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 Google's prominent use of XMLHttpRequest dramatically demonstrated that vastly improved UIs for web apps were possible, it was Jesse James Garrett's 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, I'll 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 object's 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 it's 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 (that's 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 page's HTML, often the content of a <div> tag.

An Ajax request to the server can also return any arbitrary data, but I'll 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 view's 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:

				
<html>
<head>
<title>Ajax Demo</title>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<h1>What time is it?</h1>
<div id="time_div">
I don't have the time, but


<%= link_to_remote( "click here",
:update => "time_div",
:url =>{ :action => :say_when }) %>
and I will look it up.
</div>
</body>
</html>

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.

What Time is it before clicking
Figure 1. Before clicking on the link

My controller class looks like:

				
class DemoController < ApplicationController
def index
end
def say_when
render_text "<p>The time is <b>" + DateTime.now.to_s + "</b></p>"
end
end

What Time is it after clicking
Figure 2. After clicking on the link

The index action handler doesn't 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.

It's 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 won't disappear, so I can click on it repeatedly and watch the addition of new time reports.

What Time is it appending new content
Figure 3. The position option inserts new content

The web page doesn't 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.

Using form_remote_tag

The form_remote_tag() helper is similar to link_to_remote() except that it also sends the contents of an HTML form. This means that the action handler can use user-entered data to formulate the response. This example displays a web page that shows a list and an Ajax-enabled form that lets users add items to the list.

My view template (index.rhtml) looks like:

				
<html>
<head>
<title>Ajax List Demo</title>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<h3>Add to list using Ajax</h3>


<%= form_remote_tag(:update => "my_list",
:url => { :action => :add_item },
:position => "top" ) %>
New item text:
<%= text_field_tag :newitem %>
<%= submit_tag "Add item with Ajax" %>
<%= end_form_tag %>
<ul id="my_list">
<li>Original item... please add more!</li>
</ul>
</body>
</html>

Notice the two parts in bold. They define the beginning and end of the form. Because the form started with form_remote_tag() instead of form_tag(), the application will submit this form using XMLHttpRequest. The parameters to form_remote_tag() should look familiar:

  • The update parameter specifies the id of the DOM element with content to update by the results of executing the action--in this case, my_list.
  • The url parameter specifies the server-side action to call--in this case, an action named add_item.
  • The position parameter says to insert the returned HTML fragment at the top of the content of the my_list element--in this case, a <ul> tag.

List Demo before adding items
Figure 4. Before adding any items

My controller class looks like:

				
class ListdemoController < ApplicationController
def index
end
def add_item
render_text "<li>" + params[:newitem] + "</li>"
end
end

The add_item action handler constructs an HTML list item fragment containing whatever text the user entered into the newitem text field of the form.

List Demo after adding list items
Figure 5. After adding several new list items

Using Observers

Rails lets you monitor the value of a field and make an Ajax call to an action handler whenever the value of the field changes. The current value of the observed field is sent to the action handler in the post data of the call.

A very common use for this is to implement a live search:

				
<label for="searchtext">Live Search:</label>
<%= text_field_tag :searchtext %>
<%= observe_field(:searchtext,
:frequency => 0.25,
:update => :search_hits,
:url => { :action => :live_search }) %>
<p>Search Results:</p>
<div id="search_hits"></div>

This code snippet monitors the value of a text field named searchtext. Every quarter of a second, Rails checks the field for changes. If the field has changed, the browser will make an Ajax call to the live_search action handler, displaying the results in the search_hits div.

You can see an actual demonstration of this live search on my weblog. The search box is in the upper-right corner. Try typing enterprise or rails and see what you get.

To Use or Not Use (Ajax, That Is)

When you use Ajax techniques to update portions of a web page, the user gains responsiveness and fluidity. However, the user also loses the ability to bookmark and to use the browser's back button. Both of these drawbacks stem from the same fact: the URL does not change because the browser has not loaded a new page.

Don't use Ajax just because it's cool. Think about what makes sense in your web app's user interface.

For example, if a web page displays a list of accounts with operations on the displayed list like adding, deleting, and renaming accounts, these are all good candidates for Ajax. If the user clicks on a link to show all invoices that belong to an account, that's when you should display a new page and avoid Ajax.

This means that the user can bookmark the accounts page and invoices page, and use the back and forward buttons to switch between them. The user can't bookmark the operations within one of these lists or use the back button to try to undo an operation on the list (both of which you would probably want to prevent in a traditional web app, as well).

Odds 'n' Ends

I'd like to bring a couple of really cool things to your attention, but I won't be going into any detail.

Web pages that upload files are often frustrating to users because the user receives no feedback on the status of the upload while it progresses. Using Ajax, you can communicate with the server during the upload to retrieve and display the status of the upload. Sean Treadway and Thomas Fuchs have implemented a live demonstration of this using Rails and a video on how to implement it.

The Prototype JavaScript library that Rails uses also implements a large number of visual effects. The Effects Demo Page has a live demonstration of these effects along with JavaScript calls to use them

You can find more detailed information about these and other Ajax features of Rails in Chapter 18 of Agile Web Development with Rails.

Parting Thoughts

The Web has come a long way since the days of isolated web sites serving up static pages. We are slowly moving into a new era where sites are dynamically interconnected, web APIs allow us to easily build on top of existing services, and the web user interface is becoming more fluid and responsive. Ajax not only plays an important role in this emerging Web 2.0 saga, but also raises the bar on what people will consider to be an acceptable web application.

By all rights, adding complex Ajax features to a web application should be a lot of extra work, but Rails makes it dead simple.

分享到:
评论

相关推荐

    java计算器[收集].pdf

    开发者可以选择Java EE或.NET、LAMP(Linux、Apache、MySQL、PHP)和Ruby on Rails等平台。 3. **Java ME(微型版)**:用于移动设备和嵌入式系统,如手机、PDA和电视。随着Google的Android平台发布,Java ME受到了...

    laravel-vue-master_laravelvue_laravel+vue_

    Laravel是由Taylor Otwell开发的一个开源PHP框架,其设计灵感来源于Ruby on Rails。Laravel遵循MVC(模型-视图-控制器)架构模式,强调代码的优雅性和开发的简洁性。它提供了丰富的功能,包括路由、中间件、数据库...

    burger-basic::hamburger::couch_and_lamp:带有React 16的演示汉堡

    该项目是通过引导的。 您将在下面找到一些有关如何执行...Ruby on Rails 在开发中代理API请求 配置代理后出现“无效的主机头”错误 手动配置代理 配置WebSocket代理 在开发中使用HTTPS 在服务器上生成动态&lt;met

    《数据结构》(02331)基础概念

    内容概要:本文档《数据结构》(02331)第一章主要介绍数据结构的基础概念,涵盖数据与数据元素的定义及其特性,详细阐述了数据结构的三大要素:逻辑结构、存储结构和数据运算。逻辑结构分为线性结构(如线性表、栈、队列)、树形结构(涉及根节点、父节点、子节点等术语)和其他结构。存储结构对比了顺序存储和链式存储的特点,包括访问方式、插入删除操作的时间复杂度以及空间分配方式,并介绍了索引存储和散列存储的概念。最后讲解了抽象数据类型(ADT)的定义及其组成部分,并探讨了算法分析中的时间复杂度计算方法。 适合人群:计算机相关专业学生或初学者,对数据结构有一定兴趣并希望系统学习其基础知识的人群。 使用场景及目标:①理解数据结构的基本概念,掌握逻辑结构和存储结构的区别与联系;②熟悉不同存储方式的特点及应用场景;③学会分析简单算法的时间复杂度,为后续深入学习打下坚实基础。 阅读建议:本章节内容较为理论化,建议结合实际案例进行理解,尤其是对于逻辑结构和存储结构的理解要深入到具体的应用场景中,同时可以尝试编写一些简单的程序来加深对抽象数据类型的认识。

    【工业自动化】施耐德M580 PLC系统架构详解:存储结构、硬件配置与冗余设计

    内容概要:本文详细介绍了施耐德M580系列PLC的存储结构、系统硬件架构、上电写入程序及CPU冗余特性。在存储结构方面,涵盖拓扑寻址、Device DDT远程寻址以及寄存器寻址三种方式,详细解释了不同类型的寻址方法及其应用场景。系统硬件架构部分,阐述了最小系统的构建要素,包括CPU、机架和模块的选择与配置,并介绍了常见的系统拓扑结构,如简单的机架间拓扑和远程子站以太网菊花链等。上电写入程序环节,说明了通过USB和以太网两种接口进行程序下载的具体步骤,特别是针对初次下载时IP地址的设置方法。最后,CPU冗余部分重点描述了热备功能的实现机制,包括IP通讯地址配置和热备拓扑结构。 适合人群:从事工业自动化领域工作的技术人员,特别是对PLC编程及系统集成有一定了解的工程师。 使用场景及目标:①帮助工程师理解施耐德M580系列PLC的寻址机制,以便更好地进行模块配置和编程;②指导工程师完成最小系统的搭建,优化系统拓扑结构的设计;③提供详细的上电写入程序指南,确保程序下载顺利进行;④解释CPU冗余的实现方式,提高系统的稳定性和可靠性。 其他说明:文中还涉及一些特殊模块的功能介绍,如定时器事件和Modbus串口通讯模块,这些内容有助于用户深入了解M580系列PLC的高级应用。此外,附录部分提供了远程子站和热备冗余系统的实物图片,便于用户直观理解相关概念。

    某型自动垂直提升仓储系统方案论证及关键零部件的设计.zip

    某型自动垂直提升仓储系统方案论证及关键零部件的设计.zip

    2135D3F1EFA99CB590678658F575DB23.pdf#page=1&view=fitH

    2135D3F1EFA99CB590678658F575DB23.pdf#page=1&view=fitH

    agentransack文本搜索软件

    可以搜索文本内的内容,指定目录,指定文件格式,匹配大小写等

    Windows 平台 Android Studio 下载与安装指南.zip

    Windows 平台 Android Studio 下载与安装指南.zip

    Android Studio Meerkat 2024.3.1 Patch 1(android-studio-2024.3.1.14-windows-zip.zip.002)

    Android Studio Meerkat 2024.3.1 Patch 1(android-studio-2024.3.1.14-windows.zip)适用于Windows系统,文件使用360压缩软件分割成两个压缩包,必须一起下载使用: part1: https://download.csdn.net/download/weixin_43800734/90557033 part2: https://download.csdn.net/download/weixin_43800734/90557035

    4-3-台区智能融合终端功能模块技术规范(试行).pdf

    国网台区终端最新规范

    4-13-台区智能融合终端软件检测规范(试行).pdf

    国网台区终端最新规范

    【锂电池剩余寿命预测】Transformer-GRU锂电池剩余寿命预测(Matlab完整源码和数据)

    1.【锂电池剩余寿命预测】Transformer-GRU锂电池剩余寿命预测(Matlab完整源码和数据) 2.数据集:NASA数据集,已经处理好,B0005电池训练、B0006测试; 3.环境准备:Matlab2023b,可读性强; 4.模型描述:Transformer-GRU在各种各样的问题上表现非常出色,现在被广泛使用。 5.领域描述:近年来,随着锂离子电池的能量密度、功率密度逐渐提升,其安全性能与剩余使用寿命预测变得愈发重要。本代码实现了Transformer-GRU在该领域的应用。 6.作者介绍:机器学习之心,博客专家认证,机器学习领域创作者,2023博客之星TOP50,主做机器学习和深度学习时序、回归、分类、聚类和降维等程序设计和案例分析,文章底部有博主联系方式。从事Matlab、Python算法仿真工作8年,更多仿真源码、数据集定制私信。

    基于android的家庭收纳App的设计与实现.zip

    Android项目原生java语言课程设计,包含LW+ppt

    大学生入门前端-五子棋vue项目

    大学生入门前端-五子棋vue项目

    二手车分析完整项目,包含源代码和数据集,包含:XGBoost 模型,训练模型代码,数据集包含 10,000 条二手车记录的数据集,涵盖车辆品牌、型号、年份、里程数、发动机缸数、价格等

    这是一个完整的端到端解决方案,用于分析和预测阿联酋(UAE)地区的二手车价格。数据集包含 10,000 条二手车信息,覆盖了迪拜、阿布扎比和沙迦等城市,并提供了精确的地理位置数据。此外,项目还包括一个基于 Dash 构建的 Web 应用程序代码和一个训练好的 XGBoost 模型,帮助用户探索区域市场趋势、预测车价以及可视化地理空间洞察。 数据集内容 项目文件以压缩 ZIP 归档形式提供,包含以下内容: 数据文件: data/uae_used_cars_10k.csv:包含 10,000 条二手车记录的数据集,涵盖车辆品牌、型号、年份、里程数、发动机缸数、价格、变速箱类型、燃料类型、颜色、描述以及销售地点(如迪拜、阿布扎比、沙迦)。 模型文件: models/stacking_model.pkl:训练好的 XGBoost 模型,用于预测二手车价格。 models/scaler.pkl:用于数据预处理的缩放器。 models.py:模型相关功能的实现。 train_model.py:训练模型的脚本。 Web 应用程序文件: app.py:Dash 应用程序的主文件。 callback

    《基于YOLOv8的船舶航行违规并线预警系统》(包含源码、可视化界面、完整数据集、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    《基于YOLOv8的工业布匹瑕疵分类系统》(包含源码、可视化界面、完整数据集、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    CodeCount.exe

    此为代码审查工具 可查 文件数,字节数,总行数,代码行数,注释行数,空白行数,注释率等

    商业数据分析与Python实现:企业破产概率及抽样技术解析(复现论文或解答问题,含详细可运行代码及解释)

    内容概要:本文档涵盖了一项关于企业破产概率的详细分析任务,分为书面回答和Python代码实现两大部分。第一部分涉及对业务类型和破产状态的边际分布、条件分布及相对风险的计算,并绘制了相应的二维条形图。第二部分利用Python进行了数据处理和可视化,包括计算比值比、识别抽样技术类型、分析鱼类数据集以及探讨辛普森悖论。此外,还提供了针对鱼类和树木数据的统计分析方法。 适合人群:适用于有一定数学和编程基础的学习者,尤其是对统计学、数据分析感兴趣的大学生或研究人员。 使用场景及目标:①帮助学生掌握统计学概念如边际分布、条件分布、相对风险和比值比的实际应用;②教授如何用Python进行数据清洗、分析和可视化;③提高对不同类型抽样技术和潜在偏见的理解。 其他说明:文档不仅包含了理论知识讲解,还有具体的代码实例供读者参考实践。同时提醒读者在完成作业时需要注意提交格式的要求。

Global site tag (gtag.js) - Google Analytics