Ruby w/Sinatra:我可以举一个 jQuery AJAX 请求的例子吗?

Ruby w/Sinatra:我可以举一个 jQuery AJAX 请求的例子吗?

问题描述:

%a{:href => "/new_game?human_is_first=true", :remote => "true"}
            %span Yes

以上是我的链接.只是想知道如何处理这个.我需要能够执行一些 javascript.下面是我使用 Rails 时后面的 .js.erb 文件.

Above is my link. Just wondering how to handle this. I need to be able to execute some javascript. Below is a .js.erb file from back when I using rails.

$('.welcome_container').fadeOut(500, function(){
  $( '.shell' ).html( "<%= escape_javascript( render( :partial => "board/board" ) ) %>" );
  $('.board_container').fadeIn(500);
});

所以,我的问题是,一旦/new_game 在 app.rb 中被调用,我希望能够将一些 javascript 发送到当前页面(无需离开页面,并呈现部分)

So, my question is, Once /new_game is called in app.rb, I want to be able to send some javascript to the current page (without leaving the page, and have the partial rendered)

参见 我对您最近的另一个问题的回答 用于在生产 Sinatra 应用中发送和接收 HTML 部分的全面设置.

See my answer to your other recent question for a comprehensive setup for sending and receiving HTML partials in a production Sinatra app.

由于 Sinatra 是一个不错的轻量级框架,您可以*地(*?)提出自己的工作流程和代码来实现部分和处理此类调用.您可以选择定义一个基于正则表达式的路由,而不是我的显式每部分路由,该路由根据传递的 URL 或参数查找正确的数据.

As Sinatra is a nice lightweight framework, you are free (forced?) to come up with your own workflow and code for implementing partials and handling such calls. Instead of my explicit route-per-partial, you might choose to define a single regex-based route that looks up the correct data based on the URL or param passed.

一般来说,如果你想让 Sinatra 响应一个路径,你需要添加一个路由.所以:

In general, if you want Sinatra to respond to a path, you need to add a route. So:

get "/new_game" do
  # This block should return a string, either directly,
  # by calling haml(:foo), erb(:foo), or such to render a template,
  # or perhaps by calling ...to_json on some object.
end

如果您想返回一个没有布局的部分并且您正在使用视图,请确保将 layout:false 作为选项传递给帮助程序.例如:

If you want to return a partial without a layout and you're using a view, be sure to pass layout:false as an option to the helper. For example:

get "/new_game" do
  # Will render views/new_game.erb to a string
  erb :new_game, :layout => false
end

如果你想返回一个 JSON 响应,你应该设置适当的头数据:

If you want to return a JSON response, you should set the appropriate header data:

get "/new_game" do
  content_type :json
  { :foo => "bar" }.to_json
end

如果您真的想从处理程序返回原始 JavaScript 代码,然后执行该代码...那么,返回 JS 的方法如下:

If you really want to return raw JavaScript code from your handler and then execute that...well, here's how you return the JS:

get "/new_game" do
  content_type 'text/javascript'
  # Turns views/new_game.erb into a string
  erb :new_game, :layout => false
end

由你来接收 JS 并*不寒而栗* eval() 它.

It's up to you to receive the JS and *shudder* eval() it.