Ruby w/ Sinatra: Could I have an example of a jQuery AJAX request?

后端 未结 1 1318
执念已碎
执念已碎 2021-02-11 04:15
%a{:href => \"/new_game?human_is_first=true\", :remote => \"true\"}
            %span Yes

Above is my link. Just wondering how to handle this. I

相关标签:
1条回答
  • 2021-02-11 04:50

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

    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.

    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
    

    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
    

    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
    

    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
    

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

    0 讨论(0)
提交回复
热议问题