rails response_to format.js API [英] rails respond_to format.js API

查看:38
本文介绍了rails response_to format.js API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名经验丰富的 JAVA 和 C++ 开发人员,我正在努力了解 Rails 的工作原理.

I am an experienced JAVA and C++ developer and I am trying to understand how rails works.

我在下面得到了这个代码:

I got this code below:

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,但我找不到..

and I've been searching the api that defines what I can pass inside the format.js {} but I could not find..

首先:format.js是什么语句,是变量吗?

first of all: what kind of statement is format.js, is that a variable?

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

and most important: what attributes can I pass into format.js {} ? can you pass the direct link? I've searched over the http://api.rubyonrails.org/

推荐答案

respond_to do |format|
  format.js # actually means: if the client ask for js -> return file.js
end

js 此处指定控制器方法将作为响应发回的 MIME 类型;
默认 Rails mime-types.
如果您也尝试使用 format.yaml:

js here specifies a mime-type that the controller method would send back as a response;
Default Rails mime-types.
If you try also with format.yaml:

respond_to do |format|
  format.js
  format.yaml
end

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

that will mean that your controller will return yml or js depending on what the client-side is asking;

{} 就 ruby​​ 而言是 阻止;如果你没有指定任何 rails 会尝试从 app/views/[contoller name]/[controller method name].[html/js/...]

{} in terms of ruby is a block; If you don't specify any rails will try to render a default file from 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 中.

will look for /app/views/some/hello.js.erb; // at least in 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

这篇关于rails response_to format.js API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆