使用link_to更新内容:remote =>真正

时间:2011-08-24 06:47:59

标签: javascript ruby-on-rails ruby ajax

我目前正在尝试更新特定的< div>我的页面上的元素,其中的内容由特定控制器的操作发回。我目前已经实现了这样:

查看:

link_to "Country: #{@vacancy.country.name}", semantic_country_url(@vacancy.country.id), :remote => true, :update => :semantic

控制器:

class SemanticController < ApplicationController
  # This action will communicate with DBPedia to retrieve information using the SPARQL endpoint
  # about the name of the specified city.
  def country
    country = Country.find params[:id]
    engine = SemanticSearchEngine.new
    @country = engine.country_information country.name, 'en'
    render(:update) { |page| page.replace_html 'semantic', :partial => 'semantic/country', :layout => false}
  end
end

这在控制器中起到了作用,并更新了&lt; div&gt;在包含链接的页面中使用id“semantic”。 但是,我不想在我的控制器中使用这个javascript逻辑,但是我希望将它放在一个单独的jrs文件中( 我使用HAML,所以它可能是a.haml.jrs文件< / EM> )。

但我不明白我应该怎么做。我尝试创建一个包含JavaScript的jrs文件来执行更新,但是当我调用该操作时,我可以在Firebug中看到JavaScript返回,但没有更新。

有人可以向我解释我是如何让它发挥作用的吗?

修改 的 我已将country.js.erb文件添加到包含以下代码的应用程序中:

$("semantic").replace();
$("semantic").insert("<p>#{@country.abstract.value}</p><p>#{@country.comment.value}</p><p>Currency: #{@country.currency.value}</p><p>Population: #{@country.population.value}</p><p>Capital: #{@country.capital.value}</p>");

在控制器中,我将渲染线放在注释中,让rails根据请求选择正确的渲染模板。这通常应该是country.js.haml文件。查看服务器开发日志时,单击链接时会看到以下条目:

  

于8月24日星期三09:05:52开始获取127.0.0.1的GET“/ semantic / country / 5”   +0200 2011由SemanticController#country处理为JS
  参数:{“id”=&gt;“5”}国家/地区加载(2.0ms)SELECT countries。*   FROM countries WHERE countriesid = 5 LIMIT 1已呈现   semantic / country.js.haml(4.0ms)在944ms内完成200 OK(浏览次数:   70.0ms | ActiveRecord:2.0ms)

因此我们可以得出结论,远程链接正在按预期工作。返回的Javascript是:

$("semantic").replace();
$("semantic").insert("<p>#{@country.abstract.value}</p><p>#{@country.comment.value}</p><p>Currency: #{@country.currency.value}</p><p>Population: #{@country.population.value}</p><p>Capital: #{@country.capital.value}</p>");

我认为这不应该是它应该是什么?

EDIT2 的 将文件重命名为country.js.erb并插入以下代码:

$('semantic').replace();
$('semantic').insert('<p><%= @country.abstract.value %></p><p><%= @country.comment.value%></p><p>Currency: <%@country.currency.value%></p><p>Population: <%=@country.population.value%></p><p>Capital: <%=@country.capital.value%></p>');

来自服务器的响应是HTTP 200,其中包含以下内容:

$('semantic').replace();
$('semantic').insert('<p>The United Kingdom of Great Britain and Northern Ireland (commonly known as the United Kingdom, the UK, or Britain) is a country and sovereign state located off the northwestern coast of continental Europe. It is an island nation, spanning an archipelago including Great Britain, the northeastern part of the island of Ireland, and many smaller islands. Northern Ireland is the only part of the UK with a land border with another sovereign state, sharing it with the Republic of Ireland. Apart from this land border, the UK is surrounded by the Atlantic Ocean, the North Sea, the English Channel and the Irish Sea. Great Britain is linked to continental Europe by the Channel Tunnel. The United Kingdom is a constitutional monarchy and unitary state consisting of four countries: England, Northern Ireland, Scotland and Wales. It is governed by a parliamentary system with its seat of government in London, the capital, but with three devolved national administrations of varying powers in Belfast, Cardiff and Edinburgh, the capitals of Northern Ireland, Wales and Scotland respectively. The Channel Island bailiwicks of Jersey and Guernsey, and the Isle of Man are Crown Dependencies, which means they are constitutionally tied to the British monarch but are not part of the UK. The UK has fourteen overseas territories that are not constitutionally part of the UK. These territories are remnants of the British Empire, which at its height in 1922 encompassed almost a quarter of the world's land surface, the largest empire in history. British influence can still be observed in the language, culture and legal systems of many of its former colonies. The UK is a developed country, with the world's sixth largest economy by nominal GDP and the sixth largest by purchasing power parity. It was the world's first industrialised country and the world's foremost power during the 19th and early 20th centuries, but the economic and social cost of two world wars and the decline of its empire in the latter half of the 20th century diminished its leading role in global affairs. The UK nevertheless remains a great power with leading economic, cultural, military, scientific and political influence. It is a recognised nuclear weapons state while its military expenditure ranks third or fourth in the world, depending on the method of calculation. It is a Member State of the European Union, a permanent member of the United Nations Security Council, a member of the Commonwealth of Nations, G8, G20, NATO, OECD and the World Trade Organization.</p><p>The United Kingdom of Great Britain and Northern Ireland (commonly known as the United Kingdom, the UK, or Britain) is a country and sovereign state located off the northwestern coast of continental Europe. It is an island nation, spanning an archipelago including Great Britain, the northeastern part of the island of Ireland, and many smaller islands. Northern Ireland is the only part of the UK with a land border with another sovereign state, sharing it with the Republic of Ireland.</p><p>Currency: </p><p>Population: 62041708</p><p>Capital: London</p>');

但内容仍未插入...

编辑3 我的一位同事说,代码没有约束力。 例如,警报('oops')被触发,但是当我们尝试使用$('name')选择和元素时,它返回null,即使我们知道的东西肯定存在于firebug控制台中。所以似乎缺少了一些东西,但我不知道是什么。

编辑4 创建了一个包含以下代码的新javascript文件:

document.observe("dom:loaded", function(){
$('#semantic')
    .bind("ajax:success", function(evt, data, status, xhr){
        // Since we're dealing with ajax call, we'll handle the response as JavaScript
        eval(xhr.responseText);
    })
    .bind("ajax:error", function(evt, data, status, xhr){
        // Insert a custom error message when something goes wrong
        $('#semantic').replace();
        $('#semantic').insert('<p>A problem occured retrieving the information.</p>');
    });
 });

显然根据http://www.alfajango.com/blog/rails-3-remote-links-and-forms/我需要绑定我自己的回调,我已经用上面的脚本完成了,但仍然没有骰子......

3 个答案:

答案 0 :(得分:1)

终于解决了这一切:

创建了一个Javascript文件来绑定回调

document.observe("dom:loaded", function(){
    $('semantic')
        .observe("ajax:success", function(evt, data, status, xhr){
            alert("success");
            // Since we're dealing with ajax call, we'll handle the response as JavaScript
            eval(xhr.responseText);
        })
        .observe("ajax:error", function(evt, data, status, xhr){
            alert("failed");
            // Insert a custom error message when something goes wrong
            $('semantic').replace();
            $('semantic').insert('<p>A problem occured retrieving the information.</p>');
        });
});

依赖于包含的Prototype.js文件,大多数Web示例使用jquery,因此必须调整多个调用以符合原型标准。

创建js.erb文件

$('semantic').innerHTML = "";
$('semantic').insert("<p><%= CGI::escape(@country.abstract.value) %></p><p><%= CGI::escape(@country.comment.value)%></p><p>Currency: <%= CGI::escape(@country.currency.value) %></p><p>Population: <%= CGI::escape(@country.population.value) %></p><p>Capital: <%= CGI::escape(@country.capital.value) %></p>");

这里的问题是$('semantic')。replace(),这是出于某种原因删除元素而不是清除它。

通过这些更改,远程呼叫按预期工作。

答案 1 :(得分:0)

您的国家/地区操作会在您告知时自动呈现country.js. [format]文件。只需将js / js生成代码放入该文件中,并在底部的控制器中执行类似的操作:

respond_to do |format|
  format.js
end

答案 2 :(得分:0)

不应$("semantic")$("#semantic")