【问题标题】:Issue with render or redirect_to in rails during ajax call在 ajax 调用期间,rails 中的 render 或 redirect_to 出现问题
【发布时间】:2013-10-08 16:56:52
【问题描述】:

我正在尝试在 Rails 中使用 ajax 请求(设置 remote: :true for form)进行重定向。这是我遇到的问题。

在控制器中,我有:

def create
  user = User.new
  user.attributes = params[:user]

   if user.save
    if request.xhr?
      flash[:notice] = "User successfully created"
      render js: %('#{user_url(user.id)}')
    end
  else
    if request.xhr?
      render partial: "form"
    else
      render action: 'new'
    end
  end
end

在模型中,

class user
  validates :total_amount, presence: true, numericality: {greater_than: 0}
end

在视图中,javascript是:

$("#new_user").bind("ajax:success", function(evt, data){
if(data.length < 300){
    window.location.replace(data.replace(/['\s]/gi, '')); # on success rendering the url. 
  }
  else {
    $("#errors").html($(data)); # if there are any errors, i have a div tag around form, which will replace the form html
  }
});

当我点击提交时(它是一个 ajax 请求),用户的总金额为 0.0(这是必需的),我得到验证错误,这是预期的行为(并且显示验证错误,这是 else在 javascript 中的一部分)。 现在我输入金额为 1.0 并单击提交(这也是一个 ajax 请求)。它不会出现在 javascript 中的 if 部分。

我在这里做错了什么?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby ajax


    【解决方案1】:

    您应该使用ajax:errorajax:success 作为两个不同的回调,而不是检查数据的长度。错误回调显示错误,成功重定向。

    回调:https://github.com/rails/jquery-ujs/wiki/ajax

    【讨论】:

    • 这两种情况都会触发ajax:success。不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多