jquery - rails : returning a controller object to AJAX caller

标签 jquery ruby-on-rails ajax

我正在使用 AJAX 调用 Rails Controller ,拉取一条记录,然后将该记录返回到 AJAX 调用。我的 AJAX 请求如下(我使用的是 CoffeScript):

jQuery ->
  $.ajax
    type: 'GET',
    url: '/reports',
    dataType: 'script',
    success: (response) ->
      console.log response
      return
    error: (response) ->
      console.log response
      return

我的 Controller 如下:

class ReportsController < ApplicationController

  def report
    @test_result = TestResult.first

    respond_to do |format|
      format.js { render json: @test_result.to_json }
      format.html
    end
  end

end

现在,我可以在 AJAX 中访问该对象,但通过错误函数 (error: (response) ->) 而不是成功函数 (success: (response)->)。为什么即使 xhr 调用的状态为 200 或 ok,响应也不会发送到 success 函数?我想不明白。

最佳答案

您需要使用 dataType: 'json' 进行 AJAX 调用,并从 Controller 返回 format.json 以及状态代码以及 AJAX 响应。

jQuery ->
  $.ajax
    type: 'GET',
    dataType: 'json',
    url: '/reports',
    dataType: 'script',
    success: (response) ->
      console.log response
      return
    error: (response) ->
      console.log response
      return

Controller

def report
  @test_result = TestResult.first

  respond_to do |format|
    format.json { render json: @test_result.to_json, status: :success }
    format.html
  end
end

关于jquery - rails : returning a controller object to AJAX caller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46868566/

相关文章:

ruby-on-rails - ActiveRecord::StatementInvalid: PG::Error: ERROR: cannot execute UPDATE in a read-only transaction 错误在 Heroku

javascript - 如何使用 jQuery/Ajax 执行 MySQL 查询

javascript - 在ajax调用中以JSON形式接收jsp响应

javascript - 在窗口调整大小时重新加载 jQuery Carousel 以将方向从垂直更改为水平

javascript - 验证选择字段

javascript - 使用带有附加功能的 ng-model 获取值(value) - Javascript

javascript - OnClick 发送到 Ajax

javascript - 向左滑动或向右滑动不更改页面

ruby-on-rails - rails : NameError: uninitialized constant OrderItem

ruby-on-rails - 由于 sqlite3 gem 错误,Heroku 部署失败