Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery Rails:将控制器对象返回给AJAX调用者_Jquery_Ruby On Rails_Ajax - Fatal编程技术网

Jquery Rails:将控制器对象返回给AJAX调用者

Jquery Rails:将控制器对象返回给AJAX调用者,jquery,ruby-on-rails,ajax,Jquery,Ruby On Rails,Ajax,我使用AJAX调用Rails控制器,提取一条记录,然后将该记录返回到AJAX调用。我的AJAX请求如下(我使用的是CoffeScript): 我的控制器如下所示: class ReportsController < ApplicationController def report @test_result = TestResult.first respond_to do |format| format.js { render json: @test_re

我使用AJAX调用Rails控制器,提取一条记录,然后将该记录返回到AJAX调用。我的AJAX请求如下(我使用的是CoffeScript):

我的控制器如下所示:

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)->
)而不是AJAX方法的成功函数(
success:(response)->
)。为什么即使xhr调用的状态为200或ok,响应也不会发送到success函数?我想不出来

您在ajax配置中的URL应该是
'/reports/report'
,因为ajax中的URL是
'/controller/action'
,请尝试使用
数据类型:“json”
,因为这是您正在从服务器查看的内容。

您需要使用
数据类型进行AJAX调用:“json”
,并在控制器的AJAX响应中返回
format.json

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

def report
  @test_result = TestResult.first

  respond_to do |format|
    format.json { render json: @test_result.to_json, status: :success }
    format.html
  end
end
def show
    @type = Type.find(params[:id])
    respond_to do |format|
      format.json { render json: @type.to_json, status: 200 }
      format.html
    end
  end

我提出了自己的解决办法。我希望它能帮助你

==控制器

def report
  @test_result = TestResult.first

  respond_to do |format|
    format.json { render json: @test_result.to_json, status: :success }
    format.html
  end
end
def show
    @type = Type.find(params[:id])
    respond_to do |format|
      format.json { render json: @type.to_json, status: 200 }
      format.html
    end
  end
==咖啡文件

type_changed = (id) ->
  $.ajax
    type: 'GET'
    , url: "/types/#{id}"
    success: (data) ->
      console.log('Success')
      console.log(data)
      return
    error: (data) ->
      console.log('Error')
      console.log(data)
      return