【问题标题】:Making an ajax request and returning success in rails action在 Rails 操作中发出 ajax 请求并返回成功
【发布时间】:2012-02-27 12:44:04
【问题描述】:

我正在尝试从操作中获取一些 json,但我遇到了问题。

我知道你可以返回“format.js”并返回一个“.js.erb”文件,但是......想象一下我有一个返回一些东西的动作,我想以两种不同的方式处理它。我不能在同一个 .js.erb 上使用这两种不同的方式,因为当我返回它时,两种方式都会被执行,对吧?我的意思是,当我返回该文件时,该文件将被完全处理。

所以我尝试使用jQuery的方式。

我有:

# GET /posts/slug/hidden_content.json
def hidden_content
  @post = Post.find(params[:id])
  @post = hidden_post_part(@post.body)

  respond_to do |format|
    format.json { render json: @post, :status => :ok}
  end
end

在 controller.coffee 中:

$ ->
  # Render hidden part of post
  $(".showallpost img").click( ->
    post_url = $(this).next().attr("href").split("/").pop();
    $.ajax
      url: Routes.hidden_content_path(post_url),
      type: "GET",
      contentType: "application/json",
      success: (data) ->
        console.log "foo"
  );

GET 完美运行,它返回我需要的内容,但从未调用成功函数,我没有看到“foo”日志。

我猜这个动作应该返回一些东西来告诉调用者 GET 是成功的。 (我尝试使用 :status 没有运气)。

所以我无法使用我的 GET 数据。

想法?

【问题讨论】:

  • 当您尝试使用 dataType: "JSON" 并删除 contentType 选项时会怎样?或者针对相同的 URL 发出请求,但将 .json 附加到它。问题是 jQuery 将此归类为失败的请求,因为响应格式与预期的格式不匹配。
  • @TanelSuurhans 我尝试了 dataType 并且 .json 在 url 中,没有触发成功。还有 Ryan github.com/railsware/js-routes 只是一个 js 脚本,可以帮助您处理 rails 路线,得心应手。

标签: jquery ruby-on-rails json get


【解决方案1】:

好像我的控制器返回的是纯 html 而不是 json,所以当我使用时

dataType: 'json'

我需要使用:

dataType: 'html'

有点奇怪,因为它应该返回一些 json,但它确实有效。

感谢 Mike Johnson:jquery doesn't call success method on $.ajax for rails standard REST DELETE answer

【讨论】:

    【解决方案2】:

    在你的 js.erb 中,你可以放一个

    <% if success %>
      some javascript you want to execute on success
    <% else %>
      some stuff you want to do on failure
    <% end %>
    

    【讨论】:

    • 问题是我想从不同的视图使用该操作并以其他方式使用数据。该解决方案不起作用,这就是我想以旧方式使用 ajax 的原因。
    【解决方案3】:

    我尝试了一段非常相似的代码,它可以工作 -

    $ -> 
      # Render hidden part of post
      $(".showallpost").click ->
        #post_url = $(this).next().attr("href").split("/").pop();
        $.ajax
          url: "/posts/1.json", #Routes.hidden_content_path(post_url),
          type: "GET",
          contentType: "application/json",
          success: (data) ->
            console.log "foo"
    

    我建议您在发送请求之前检查 url 是什么。它可能只是被 Jquery 的跨域请求检查所困,根本不会被触发——当我使用“localhost:3000/posts/1.json”作为 url 而不是“posts/1.json”时发生在我身上/p>

    【讨论】:

      猜你喜欢
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多