【问题标题】:Handle AJAX callback either render partial or redirect处理 AJAX 回调或者渲染部分或者重定向
【发布时间】:2018-11-07 18:28:13
【问题描述】:

我有一个 AJAX 调用来加载一个模式,但如果 consent settings 关闭 redirect_to 设置页面,我有一个 before_action

AJAX 调用

$(document).on 'click', '#add-consent-form-template, #edit-consent-form-template', (e) ->
  $.ajax(url: $(this).attr('data-url')).done (html) ->
    $("#modal-consent-form-content").html html
    $("#modal-consent-form").modal('show')
    $('.date_picker').each ->
      $(this).datepicker
        showOn: 'both'
        dateFormat: 'mm-dd-yy'
        altFormat: 'yy-mm-dd'
        altField: $(this).next()
        minDate : 0
    $('.ui-datepicker-trigger').addClass('fa fa-calendar fa-lg mar-left-10')
    $('.description .widget').height($('.study-graph .widget').height())
  e.preventDefault()

正常情况(如果同意设置为 ON)

render partial: 'add_consent_form_template_modal', layout: false

错误案例(如果同意设置为关闭)

set_flash(error: 'Consent Forms are disabled. Please turn on Consent Forms first.')
redirect_to edit_study_path(id: @study)

问题

redirect_to 的情况下,它会在模态中呈现整个设置页面。如何处理 AJAX 回调以呈现部分或重定向到设置页面?

【问题讨论】:

  • 你不能从 ajax 调用重定向。
  • 是否有中止 AJAX 回调的方法?那如果它redirect_to 而不是来AJAX 回调?
  • 不要使用redirect_to。只需返回path 即可重定向并在客户端使用window.location = path
  • 是的,这就是我实际尝试的方法,但我如何确定我收到的是html 还是path
  • 按状态码。

标签: ruby-on-rails ajax coffeescript


【解决方案1】:

对于特定情况,当您的控件正在进行 AJAX 回调并且您想要 redirect_tosettings 并且不想在模式上呈现它时,只需将 nil 作为 HTML 传递。

set_flash(error: 'Consent Forms are disabled. Please turn on Consent Forms first.')
render html: nil

在您的 Javascript/CoffeeScript 中,您可以简单地检查您的 length html

$(document).on 'click', '#add-consent-form-template, #edit-consent-form-template', (e) ->
  $.ajax(url: $(this).attr('data-url')).done (html) ->
    if html.length > 0
      $("#modal-consent-form-content").html html
      $("#modal-consent-form").modal('show')
      $('.date_picker').each ->
        $(this).datepicker
          showOn: 'both'
          dateFormat: 'mm-dd-yy'
          altFormat: 'yy-mm-dd'
          altField: $(this).next()
          minDate : 0
      $('.ui-datepicker-trigger').addClass('fa fa-calendar fa-lg mar-left-10')
      $('.description .widget').height($('.study-graph .widget').height())
    else
      window.location.href = <Link to your settings page>
  e.preventDefault()

【讨论】:

    【解决方案2】:

    在你的行动中

    编写以下代码,请根据您的要求添加if条件

    if consent == ON
       render partial: 'add_consent_form_template_modal', layout: false
    else
       set_flash(error: 'Consent Forms are disabled. Please turn on Consent Forms first.')
    redirect_to edit_study_path(id: @study) and return
    end
    

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 1970-01-01
      • 2015-07-04
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多