【问题标题】:How to pass json response from controller to ajax call in rails如何将json响应从控制器传递到rails中的ajax调用
【发布时间】:2014-03-03 14:16:16
【问题描述】:

这是我在 js 文件中的 ajax 调用部分:

$("#sign_submit").click(function(){
            email_id = $("#user_email").val();
            password = $("#user_password").val();

            data =  {email: email_id, password: password };
            url = user/sign_in';

            $.ajax({
                url: url,
                data:  data,
                cache: false,
                type: "post",
                success: function(data){
                    console.log(data);
                }
              });
});

这是我的控制器动作:

  def create
    @user = User.find_by_email(params['email'])
    if @user.nil?
      respond_to do |format|
        format.json {render :json => {:response => 'User is invalid'} }     #how to pass json response here. 
      end
    end

    if @user.check_valid_user?(params['password'])
      set_dashboard_location
      set_current_user(session[:customer_id])
      render js: %(window.location.href='#{session["spree_user_return_to"]}')
    else
       #redirect_to '/' and return 
       #how to psas json response here.
    end
  end

在创建操作(其他部分)中,我需要将关于(无效用户/无效用户凭据)的 json 响应传递给我的 ajax 调用,我可以在查看页面上提醒用户。

【问题讨论】:

    标签: jquery ruby-on-rails ajax


    【解决方案1】:

    我很难理解问题出在哪里,但我会尽力帮助您。

    从 Rails 控制器渲染 json 的基本命令是

    render json: @user
    

    例如。我看到你写了类似的东西,但在某个块内。 当你写

    respond_to do |format|
      format.json { render json: @foo }
    end
    

    只有当查询的 url 以 .json 结束时才会发生 json 渲染(查询的格式) 所以这里url = user/sign_in.json 将呈现json,但url = user/sign_in 将假定格式为html(默认格式,您可以在路由定义中更改)并且不会呈现任何内容。

    如果你需要渲染 json,不管 url。不要把它放在块respond_to。如果您需要 2 种不同的行为(如果是 ajax 调用或其他调用),请使用 url foo/bar.json

    如果您在 rails 根文件夹中运行 rake routes,您将看到类似 /users/sign_in(.:format) 的 url,这意味着 /users/sign_in.toto 会将 :format 设置为 toto

    我希望它很清楚! 如果您希望在路线中设置默认格式:

    How to set the default format for a route in Rails?

    【讨论】:

    • 我理解你的解释。并试图在 json: 中传递@user,但是当它为 nil 时,它应该执行我们的 if 块并将 nil 返回到我的 ajax 文件。但实际上它并没有将 nil 值返回给我的 ajax。如何将该 nil 值传递给 ajax?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    相关资源
    最近更新 更多