代码之家  ›  专栏  ›  技术社区  ›  nullnullnull

Rails:通过AJAX调用呈现js.erb

  •  11
  • nullnullnull  · 技术社区  · 13 年前

    从JavaScript,我通过AJAX调用一个控制器,如下所示:

    $.ajax({
      type: 'GET',
      url: '/books'
    }
    

    在我的控制器中,我有:

    def index
      render 'lightbox.js.erb'
    end
    

    在我的路线上,我有:

    resources :books do
      member do
        get :lightbox
      end
    end
    

    在lighbox.js.erb中,我有:

    alert("Hello world!");
    

    出于某种原因,警报从未被调用。无论是通过服务器还是通过Firebug,我都没有收到任何错误消息。我不知道可能出了什么问题。有什么想法吗?

    7 回复  |  直到 13 年前
        1
  •  27
  •   nullnullnull    13 年前

    事实证明,在客户端,我的JavaScript被呈现为文本。我通过查看控制台提要确认了这一点。上面写着:

    Started GET "/books/lightbox?book=4&username=tbaron&_=1344009191129" for 127.0.0.1 at 2012-08-03 10:53:11 -0500
    Processing by BooksController#lightbox as text
    

    最后两个单词应该读作“as JS”。在四处查找后,我发现了这个 blog post 这导致了令人惊讶的简单解决方案。将“dataType:script”添加到AJAX调用中:

    $.ajax({
      type: 'GET',
      url: '/books'
      dataType : 'script'
    }
    

    谢谢大家的帮助!

        2
  •  7
  •   Anthony Alberto    13 年前

    我想那是因为你需要打电话 books.js 以下为:

    $.ajax({
      type: 'GET',
      url: '/books.js',
      success: function(data) {
        eval(data);
      }
    }
    

    在索引操作中:

    def index
      respond_to do |format|
        format.js { render 'lightbox'}
      end
    end
    

    lightbox.js.erb 应该在应用程序/视图/书籍中

    如果仍然不起作用,请尝试拨打 books/index.js 您还可以使用firebug/chrome来检查服务器对您的ajax调用的响应

        3
  •  1
  •   Isaac Canan    13 年前

    您可以尝试此脚本来调用java脚本中的操作

    var post_params = {};
    var action = '/books/script_action';
    
    $.post(action, post_params).success(function (data) {
    
         eval(data);
    
    }).error(function (data) {
    
        alert("Erro to call a action controller");
    
    });
    

    在你的控制器里试试这个。我建议创建一个新动作

    def script_action
      render 'lightbox.js'
    end
    

    在路由文件中:

    match "books/script_action/" => "books#script_action"
    
        4
  •  0
  •   Peter DeWeese    13 年前

    尝试将其添加到控制器:

    respond_to :js
    
        5
  •  0
  •   tardis    10 年前

    在索引操作中,不使用布局进行渲染

    def index
      respond_to do |format|
      format.js { render 'lightbox', layout: false}
    end
    

    这是我的工作。

        6
  •  0
  •   cdouble.bhuck    8 年前

    对于任何偶然发现这一点并只想调用控制器动作的人,该控制器动作会以 js.erb 文件,我通过这种方式(在 Anthony Alberto's Awesome Answer )。

    控制器操作

    def some_action
      ..
      respond_to do |format|
        format.js { render 'some_action' }
      end
    end
    

    某些操作.js.erb

    ...
    $('#someActionWrap').html('<%= j render "some/displaypartials/action_partial" %>')
    ...
    

    Ajax调用

    var id = '<%= @someresource.id %>';
    $.get('/someresource/' + id + '/action/', null, function(data){
        eval(data)
    }, 'script');
    
        7
  •  0
  •   Brandon Minnick    8 年前

    我在link_to-helper上也有类似的问题,但使用 remote:true