基于从阿贾克斯的一个实例变量动态更新页面变量、实例、页面、动态

2023-09-10 19:57:40 作者:理想三旬

更新:我的问题得到回答,但我写了一篇博客,详细说明究竟我该怎么去了解这样做: http://lathamcity.com/posts/ajaxInRails.html

Update: My question was answered, but I wrote a blog post detailing exactly how I went about doing this: http://lathamcity.com/posts/ajaxInRails.html

我有一个网页,显示了基于Ruby对象的事情的清单。我的目标是做一个Ajax调用来获取一个新的Ruby对象,然后更新的基础上,该清单。

I have a page that shows a list of things based on a Ruby object. My goal is to make an Ajax call to get a new Ruby object and then update the list based on that.

我认为要做到这一点的方法是用谐音。我使整个列表中的code Rails的实例变量的部分文件。然后,我想Ajax调用相应的实例变量设置为新的列表,并重新渲染的部分。

I thought that the way to do this was with partials. I make the entire list a partial file with the Rails instance variable in the code. Then I want the Ajax call to set the corresponding instance variable to the new list and re-render the partial.

这是最终目标,但现在我试图做一个真正的基本版本,我只是设置一个实例变量为一个字符串,然后显示字符串。

That's the end goal, but right now I'm trying to do a really basic version of that where I just set an instance variable to a string and then show the string.

因此​​,在我的分区,我有:

So in my div, I have:

<% form_tag :action => :go , :method => :get, :remote => true  do %>
    <%= submit_tag "Go" %>
<% end %>

<div id="test"><%= render(:partial => 'test') %></div>

有一个在意见/接口_test.erb文件文件夹(我的控制器的名称),只有下面一行的内容:

There's a _test.erb file in the views/interface (the name of my controller) folder, with only the following line as its contents:

<%= @test %>

然后在我的控制器,

And then in my controller,

def go
    @test = "Hello You"
    render :update do |page|
        page.replace_html "test", :partial => "test"
    end
end

当我运行它,我得到:缺少模板接口/更新,应用程序/更新

When I run this, I get: Missing template interface/update, application/update

我不知道很多关于渲染:更新,我发现它在谷歌的例子

I don't know much about render :update, I found it in an example on Google.

我在做什么错,是造成这个问题,我怎么能解决这个问题?我要对这个正确的方式,或是否有更好的办法做到这一点?

What am I doing wrong that is causing this problem and how can I fix it? Am I going about this the right way or is there a better way to do it?

推荐答案

我觉得既渲染:更新 replace_html 是pcated德$ P $ /中轨3.1去除。这样做的部分更新的标准方法是使用一个js.erb模板

I think both render :update and replace_html were deprecated/removed in rails 3.1. The standard way of doing partial updates is to use a js.erb template.

在你的控制器,告诉你的行动,以JS请求作出响应:

In your controller, tell your action to respond to js request:

@test = "Hello you"
respond_to do |format|
    format.js
end

创建JS响应模板的应用程序/视图/接口/ go.js.erb:

Create the js response template app/views/interface/go.js.erb:

$('#test').html("<%= escape_javascript(render('test', test: @test})) %>")

和改变局部code到&LT;%=测试%&GT; ,因为这不再是一个实例变量;相反,测试被传递到部分从js.erb模板参数与测试:@test

and change the partial code to <%= test %> because this is no longer an instance variable; rather, test is being passed to the partial as an argument from the js.erb template with test: @test