我正在使用 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/