【问题标题】:rails ajax request doesn't refresh datarails ajax请求不刷新数据
【发布时间】:2013-07-28 14:31:00
【问题描述】:

我在 Rails 应用程序中的 ajax 请求遇到了一些问题。

我提出一个请求,当我点击时我从链接中获取一些参数,然后我想刷新包含我数据库中的图像的部分。

这是我的ajax

    $.ajax({

        url:"gallery",
        data: { pie :categoria},
        type: "GET",
        async: true,
        dataType: "script"


    });

问题是在 rails shell 中我的参数被传递了。 但它不会对视图进行任何更改。


我的外壳:

Started GET "/gallery?pie=VibPellizcables&_=1375047201412" for 127.0.0.1 at Sun Jul 28 18:33:21 -0300 2013
Processing by GalleryController#pro as JS
  Parameters: {"pie"=>"VibPellizcables", "_"=>"1375047201412"}
  Product Load (0.1ms)  SELECT `products`.* FROM `products` WHERE `products`.`pie` = 'VibPellizcables'
  Rendered sexytoys/_algo.html.haml (0.1ms)
Completed 200 OK in 1ms (Views: 0.6ms | ActiveRecord: 0.1ms)

我想更新一个包含我的数据库中的图像的部分。

这是我要更新的部分。

  #miniDiv 

    %ul#miniRecuadro
      - @products.each do |product|
        %li.mini= image_tag product.pic.url(:thumb)

我的控制器:

      def gallery
        @products = Product.find(:all, :conditions => {:pie => params[:pie]})
        #render :partial => "algo"
        flash[:notice] = "Mensaje ENVIADO >>"
        respond_to do |format|

          format.js {render :partial => 'algo', :conditions => {:pie => params[:pie]}}
         # format.json { render :json => @products  }
        end

【问题讨论】:

    标签: ruby-on-rails ajax refresh


    【解决方案1】:

    您必须在响应或 AJAX 回调中进行替换:

    进行替换的响应

    你需要渲染一个JS文件:

    # app/controllers/gallery_controller.rb
    def pro
      ...
      respond_to do |format|
        format.js # no render here
      end
      ...
    end
    
    # app/views/gallery/pro.js.erb
    $('#your-container').html('<%= j( render partial: 'algo' )%>')
    

    我不确定这条路径,如果这条路径错误,应用程序会抱怨,你会在浏览器控制台中看到这个,因为这是 AJAX。我不知道 conditions 选项是否支持视图。

    回调做替换

    $.ajax({
    
        url:"gallery",
        data: { pie :categoria},
        type: "GET",
        async: true,
        success: function(response){
          $('#your-container').html(response);
        }
    
    
    });
    

    注意我在这里删除了dataType: 'script',因为你不想执行服务器响应。

    在这种情况下,您可以使用您正在响应的 html 进行响应:

    # gallery_controller.rb
    ...
      format.html {render :partial => 'algo', :conditions => {:pie => params[:pie]}}
    ...
    

    请注意,由于您正在呈现 html,因此我更改了您的响应格式。

    快捷方式

    最后,如果您想在页面中的容器内从服务器加载内容,您可能会对load 感兴趣:

    $('#your-container').load('gallery', { pie: categoria });
    

    【讨论】:

    • 我尝试使用“回调进行替换”选项,对我来说效果很好,非常感谢。稍后我会尝试使用其他选项再次感谢你,胡安
    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2011-07-06
    相关资源
    最近更新 更多