如何访问 laravel 中的 response()->json() 方法返回的属性
我的控制器:
$validator = Validator::make($request->all(), [
'file' => 'required|mimes:xlsx|max:10000'
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Please only upload valid Excel (.xlsx) file.'
], 422);
}
Ajax 调用:
$.ajax({
url : "{{ route('budgets.import') }}",
method:'post',
async: false,
data :new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success:function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
Swal.fire(
'Failed!',
response.message,
'error'
);
},
});
当我console.log(response.response.data.message)时我得到的结果:
未捕获类型错误:response.response 未定义
如何访问“消息”属性?
更新1
更新2
我尝试检查“网络”选项卡,然后发现状态为 500,尽管我传入了控制器 422,
但是当我点击回复时,内容是:
Illuminate\Http\JsonResponse {#1387
#data: "{"message":"Please only upload valid Excel (.xlsx) file."}"
#callback: null
#encodingOptions: 0
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1386
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:3 [
"cache-control" => "Cache-Control"
"date" => "Date"
"content-type" => "Content-Type"
]
#headers: array:3 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Wed, 19 Jan 2022 12:20:50 GMT"
]
"content-type" => array:1 [
0 => "application/json"
]
]
#cacheControl: []
}
#content: "{"message":"Please only upload valid Excel (.xlsx) file."}"
#version: "1.0"
#statusCode: 422
#statusText: "Unprocessable Content"
#charset: null
+original: array:1 [
"message" => "Please only upload valid Excel (.xlsx) file."
]
+exception: null
}
“message”属性在那里,只是无法在ajax调用中访问它。最令人沮丧的是 statusCode 是 true 422 ,但在网络选项卡中却显示 500
试试这个
response.responseJSON.message
试试这个:
var obj = JSON.parse(响应); $message = obj.message;