【问题标题】:How to set flash message on ajax success redirect如何在 ajax 成功重定向上设置 flash 消息
【发布时间】:2019-12-25 13:34:49
【问题描述】:

据我所知,我已正确遵循此问题的其他答案。但是,无论出于何种原因,我的实现都无法正常工作。

我正在发出 ajax 请求并在成功时使用 location.href 重定向,并试图弄清楚如何设置 Flash 消息。

这是在我的控制器中:

if payment_service.succeeded?
  flash.notice = 'Your subscription was set up successfully!'
  json = { success: true, redirect_path: root_path }
end

respond_to do |format|
  format.json { render json: json, status: 200 }
end

这是进行 ajax 调用的地方:

fetch('/subscriptions/confirm_payment', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ payment_method_id: result.paymentMethod.id })
}).then(function(result) {
  result.json().then(function(json) {

  if (response.error) {
    displayError(result.error);
  } else if (response.success) {
    location.href = response.redirect_path;
  }
})

我希望看到重定向到redirect_path 后显示的闪光通知。但没有显示闪光灯。

【问题讨论】:

标签: javascript ruby-on-rails ajax


【解决方案1】:

你可以使用flash.keep()方法。

它将保留flash 消息的内容以供进一步操作。 https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/Flash/FlashHash.html#method-i-keep

if payment_service.succeeded?
 flash.keep(:notice) = 'Your subscription was set up successfully!'
 json = { success: true, redirect_path: root_path }
end

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多