![](/img/trans.png)
[英]Returning model object from Controller to Ajax jquery not working in Spring mvc
[英]Rails: returning a controller object to AJAX caller
我正在使用 AJAX 調用 Rails 控制器,提取記錄,然后將該記錄返回給 AJAX 調用。 我的 AJAX 請求如下(我使用的是 CoffeScript):
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 中訪問該對象,但通過 AJAX 方法的錯誤函數( error: (response) ->
)而不是成功函數( success: (response)->
)。 為什么即使 xhr 調用的狀態為 200 或 ok,響應也不會發送到成功函數? 我想不通。
您需要使用dataType: 'json'
進行 AJAX 調用,並在控制器的 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
您在 ajax 配置中的 URL 應該是'/reports/report'
,因為 Ajax 中的 URL 是'/controller/action'
並嘗試使用dataType: 'json'
,因為這是您從服務器上觀察到的。
我做了我自己的解決方案。 我希望它能幫助你。
=== 控制器
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.