我从我的React组件向我的后端Rails应用程序发出GET请求并收到成功的响应(200)但是我在数据库中保存对象列表的respose对象中缺少数据属性。这是我的Ajax请求
$.ajax({
method: 'GET',
url: '/dashboard/jobs/eligible',
dataType: 'json',
success: (response) => {
console.log(response)
}
});
当我做console.log(response.data)时,我得到'undefined'。不过,我从后端获得了一个对象的数组。
console.log(response) # [{...}]
从数据库中保存一个对象。
这是我的dashboard/jobs
控制器动作:
def eligible
@eligible_jobs = EligibleJobsDatatable.new(current_user).call
respond_to do |format|
format.html
format.js { render json: @eligible_jobs }
end
end
我没有在项目中使用任何序列化程序。
我错过了什么吗?
回答是正确的。它是一个序列化的对象。
但是,我相信您需要遵循jsonapi标准的响应。如果这是真的,我建议你使用一个gem来处理你的对象到JSON的序列化,即fast_jsonapi。
当我做console.log(response.data)时,我得到'undefined'。不过,我从后端获得了一个对象的数组。
这是应该如何工作的。
从Ajax文档:
成功
类型:Function(Anything data,String textStatus,jqXHR jqXHR)如果请求成功则调用的函数。该函数传递三个参数:从服务器返回的数据,根据dataType参数或dataFilter回调函数格式化(如果指定);描述状态的字符串;和jqXHR(在jQuery 1.4.x,XMLHttpRequest)对象。
Ajax请求接受数据参数,textStatus和请求对象。如果你想要那些,创建你的功能:
$.ajax({
method: 'GET',
url: '/dashboard/jobs/eligible',
dataType: 'json',
success: (data, status, obj) => {
console.log(data)
}
});