在 Rails 中,使用 link_to 帮助器设置 :remote => true 会产生以下输出:
<a href="#yoururl" data-remote="true">Linktext</a>
此链接在rails.js 中通过以下方式观察到:
$(document).on('click.remote', '[data-remote]', function() {
$.ajax({
url: $(this).attr('href'),
type: $(this).data('method') || 'GET',
// and so on...
});
});
因此,它实际上是用data-remote="true" 属性标记您的HTML 链接,然后通过js 处理它。然后通过DOM 评估您可以使用的js.erb 模板。 (我个人认为这是个坏主意)。
在 Sinatra 中,您可以执行几乎相同的操作:例如,使用 remote 类标记您的链接(它提供了比 rails 通过 [data-remote] 使用的一个更快的 js 查找:
<a href="#yoururl" class="remote">Your Link Text</a>
然后通过 jQuery 绑定具有远程类的链接:观察整个文档以查看源自具有远程类的元素的点击事件,就像 rails 所做的那样:
$(document).on('click.remote', '.remote', function() {
// a similar ajax call to the one rails uses
});
然后,在sinatra 和Sinatra::JSON 中回复JSON:
get '/yoururl' do
json :foo => 'bar'
end
然后对 ajax 调用的成功处理程序中的数据做你喜欢的事情。或者,您也可以使用 erb 编写的脚本进行响应(rails 对 .js.erb 所做的):
get '/yoururl' do
erb :"answer.js"
end