Ton*_*ark 11 ajax json ujs ruby-on-rails-3
我正在尝试在我的Rails 3应用程序中添加一些Ajax功能.
具体来说,我想要一个按钮,它将提交一个Ajax请求来调用我的控制器中的远程函数,该控制器随后查询API并将JSON对象返回到页面.
收到JSON对象后,我想显示内容.
所有这些都采用了新的Rails 3 UJS方法.这个在线的某个地方有一个很好的例子/教程吗?我一直无法在谷歌上找到一个.使用按钮作为入口点(即,用户单击按钮以启动此过程)的简单示例也将起作用.
编辑 让我用不同的方法尝试这个.我想让这个按钮查询一个外部API,它返回JSON,并在页面上显示该JSON.我不知道从哪里开始.按钮本身是否查询外部API?我是否需要通过控制器,让控制器查询外部API,获取JSON,并将JSON返回到此页面?如何显示/访问此JSON的内容?老实说,我找不到一个好的Rails 3.x如何处理JSON的例子......
Mat*_*ani 10
这是一个开始:
首先在视图中使用link_to方法创建按钮,例如:
=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'
Run Code Online (Sandbox Code Playgroud)
请注意,我将".json"附加到我的资源的url.这只是一个AJAX删除的例子,google link_to可以看到参数的含义.这个概念,如果您使用参数:remote设置为true来发出HTTP请求,换句话说,这将从浏览器转换为AJAX调用.
其次,编写一些javascript,以便您可以处理当用户单击步骤1的link_to时您的浏览器将进行的AJAX调用的结果.有关详细信息,您可以看到此博客文章:http://www.alfajango .COM /博客/导轨-3远程链接和表单/
我网站上的一个例子:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#pending_invitation")
.live("ajax:loading", toggleLoading)
.live("ajax:complete", toggleLoading)
.live("ajax:success", function(event, data, status, xhr) {
var response = JSON.parse(xhr.responseText)
if (response.result == "ok") {
$(this).fadeOut('fast');
}
else {
var errors = $('<div id="error_explanation"/>');
errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
$('#new_invitation_error').append(errors)
}
});
});
Run Code Online (Sandbox Code Playgroud)
在那里你可以看到我解析返回的json并根据它改变页面上的html.请注意,此js使用顶视图中定义的CCS ID和类,此处未包含这些内容.
如果您现在想要编写自己的控制器来吐出json,这里是一个例子:
class InvitationsController < ApplicationController
respond_to :html, :json
# other methods here
# ...
def destroy
@invitation = Invitation.find(params[:id])
respond_to do |format|
if @invitation
@invitation.destroy
flash[:success] = I18n.t 'invitations.destroy.success'
format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
else
format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
希望这有帮助.
| 归档时间: |
|
| 查看次数: |
16230 次 |
| 最近记录: |