我是一位经验丰富的JAVA和C++开发人员,并且试图了解Rails的工作原理。

我在下面获得此代码:

respond_to do |format|
      if @line_item.save
        format.html { redirect_to store_url }
        format.js { render :json => @line_item, :mime_type => Mime::Type.lookup('application/json'),
                :callback => 'javascriptFunction' }

并且我一直在搜索定义可以在format.js {}内部传递但无法找到的API。

首先:format.js是什么类型的语句,这是一个变量吗?

最重要的是:我可以将哪些属性传递给format.js {}?您可以通过直接链接吗?我搜索了http://api.rubyonrails.org/

最佳答案

respond_to do |format|
  format.js # actually means: if the client ask for js -> return file.js
end
js在此指定了 Controller 方法将作为响应发送回的mime类型;
Default Rails mime-types
如果您也尝试使用format.yaml:
respond_to do |format|
  format.js
  format.yaml
end

这意味着您的 Controller 将根据客户端的要求返回ymljs

用 ruby 表示的{}block;
如果您未指定任何轨道,则将尝试从app / views / [contoller name] / [controller method name]中呈现默认文件。[html / js / ...]
# app/controllers/some_controller.rb
def hello
  respond_to do |format|
    format.js
  end
end

将寻找/app/views/some/hello.js.erb; //至少在Rails v。2.3中。

如果确实指定块:
respond_to do |format|
    # that will mean to send a javascript code to client-side;
    format.js { render
        # raw javascript to be executed on client-side
        "alert('Hello Rails');",
        # send HTTP response code on header
        :status => 404, # page not found
        # load /app/views/your-controller/different_action.js.erb
        :action => "different_action",
        # send json file with @line_item variable as json
        :json => @line_item,
        :file => filename,
        :text => "OK",
        # the :location option to set the HTTP Location header
        :location => path_to_controller_method_url(argument)
      }

  end

07-24 18:43
查看更多