Rails:返回一个控制器对象给AJAX调用者
问题描述:
我打电话给Rails控制器使用AJAX,拉一条记录,然后将该记录返回给AJAX调用。我的AJAX请求如下(我使用CoffeScript):Rails:返回一个控制器对象给AJAX调用者
jQuery ->
$.ajax
type: 'GET',
url: '/reports',
dataType: 'script',
success: (response) ->
console.log response
return
error: (response) ->
console.log response
return
我的控制器如下:
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,响应如何不会进入成功功能?我想不明白。
答
您需要与dataType: 'json'
进行AJAX调用,并返回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
控制器
def report
@test_result = TestResult.first
respond_to do |format|
format.json { render json: @test_result.to_json, status: :success }
format.html
end
end
答
你在阿贾克斯配置URL应该是'/reports/report'
,因为Ajax中的URL是'/controller/action'
与dataType: 'json'
尝试,因为这是你从服务器specting什么。