【问题标题】:How do I properly handle a remote link to in Rails 4? JSON?如何正确处理 Rails 4 中的远程链接? JSON?
【发布时间】:2014-04-02 20:48:53
【问题描述】:

我有以下代码:

= link_to "#{icon('heart')} Props".html_safe, vote_picture_path(picture), class: 'tiny radius secondary button vote', method: :put, remote: true

这里是:

  # VOTE /pictures/1.json
  def vote
    respond_to do |format|
      if @picture.toggle_vote(current_user)
        format.json { render json: @picture }
      else
        format.json { render json: @picture }
      end
    end
  end

我要做的是通过以下方式更新图片的总票数:

$ ->
  $(".vote").on "ajax:success", (e, data, status, xhr) ->
    vote_count_size = $(".vote-count .size").html()
    vote_count_size_integer = parseInt(vote_count_size)
    console.info data

但让我感到困惑的是 console.info 数据。它似乎从我无法分辨的来源返回了一些东西。我正在编辑 /pictures/show.json.jbuilder 但它不会影响来自数据的内容。我想返回一个带有数据总票数的 json 结构,这样我就可以从成功回调中更新页面上的计数。

【问题讨论】:

  • 你能用bind代替on吗?

标签: javascript ruby-on-rails json


【解决方案1】:

首先,您的respond_to 块可以被大幅重构:

  # VOTE /pictures/1.json
  respond_to :json

  def vote
     @picture.toggle_vote(current_user)
     respond_with @picture
  end

这应该为您的@picture var 返回一个 JSON 对象。您必须详细说明您在console 中获得了什么数据?如果您提供您收到的数据,那将是一个巨大的帮助!

【讨论】:

  • 它返回这个:gist.github.com/ecl1pse/ea0fb3936d2ca911e311 我不知道怎么做,因为如果我编辑图片/show.jbuilder 中的内容,它不会影响这个。
  • 不确定是否需要更多信息来完成这项工作?我的困惑是我应该这样做吗?
【解决方案2】:

您应该在其中使用 javascript 文件 (vote.js.erb) 进行响应,您可以混合使用 javascript 和 erb 表达式来更改所需的页面元素:

$('.vote-count .size').html('<%=@picture.vote_count%> votes');

你的控制器看起来像:

# VOTE /pictures/1.js
def vote
  respond_to do |format|
    @picture.toggle_vote(current_user)
    format.js 
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多