0

我尝试将 pjax-rails gem 用于项目。

当我使用 gem 中的重定向方法时。浏览器将响应呈现为文本。我假设 text/javascript 而不是 script/javascript。

这是我的控制器的外观(注意 redirect_to_pjax):

 def create
@contact = Contact.new params[:contact]
if @contact.save
    flash[:notice] = "Successfully added contact"
    redirect_pjax_to :show,@contact
end

这是宝石https://github.com/rails/pjax_rails

这是方法“redirect_pjax_to”的原始实现我认为魔法发生在这里......(取自github)

 private  
def redirect_pjax_to(action, url = nil)
  new_url = url_for(url ? url : { action: action })

  render js: <<-EJS
    if (!window.history || !window.history.pushState) {
      window.location.href = '#{new_url}';
    } else {
      $('[data-pjax-container]').html(#{render_to_string("#{action}.html.erb", layout: false).to_json});
      $(document).trigger('end.pjax');

      var title = $.trim($('[data-pjax-container]').find('title').remove().text());
      if (title) document.title = title;
      window.history.pushState({}, document.title, '#{new_url}');
    }
  EJS
end

我假设 render :js 在这里需要一个 content_type ......

有没有人有同样的问题?或者更好的解决方案?

4

1 回答 1

0

你能看到你是否进行了 AJAX 调用吗?如果您从输入元素而不是锚元素创建,我认为 pjax 不会被触发

我在我的 Rails 应用程序中使用 PJAX,只需检查 PJAX 的 HTTP 请求的标头,然后执行 render :layout false。奇迹般有效。

于 2011-10-04T15:46:30.160 回答