rails respond_to format.js API

前端 未结 2 735
醉酒成梦
醉酒成梦 2020-12-04 10:25

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 @lin         


        
2条回答
  •  广开言路
    2020-12-04 10:45

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

    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
    

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

    {} 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
    

    will look for /app/views/some/hello.js.erb; // at least in Rails v. 2.3.

    If you do specify block:

    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
    

提交回复
热议问题