代码之家  ›  专栏  ›  技术社区  ›  user3574603

Rails:是否有必要将我的POST响应包装成respond-to-block?

  •  1
  • user3574603  · 技术社区  · 6 年前

    我有一个AJAX表单,它向控制器发送POST请求。控制器以JSON响应。

    在这里, reponse

      def send_form_response(response)
        render json: response
      end
    

    上面的工作很好,但我不断看到的例子,使用 respond_to . 当我将我的回答包装在 阻止。

      def send_form_response(response)
        respond_to do |format|
          format.json { render json: response }
        end
      end
    

    有什么好处吗?如果我不去,会有什么不好的事情发生吗?或者在这种情况下没有区别?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Pavan Cesar    6 年前

    respond_to 用于处理中的多个响应 controller#action

    如果客户机需要HTML来响应此操作,只需 我们以前可能会这样做,但是如果客户机需要XML,请返回 从客户端提交的HTTP Accept头格式化。)

    比如说,如果你想 send_form_response(response) 回应 HTML JSON ,那么你就这样做

    def send_form_response(response)
      respond_to do |format|
        format.html
        format.json { render json: response }
      end
    end
    

    respond_with

    respond_to :html, :xml, :json
    def send_form_response(response)
      respond_with response
    end
    

    所以,回答你的问题

    你能给我什么好处吗?

    不是在你的情况下,你只要求一个答复

    如果我不去,会有什么不好的事情发生吗?

    不是你的情况,不是。

    在这种情况下没有区别吗?

    不,一点也不。