【发布时间】:2018-01-22 17:03:43
【问题描述】:
我正在使用 ajax 写入我的模型,如果出现类似重复的错误,我需要它来引发 json 响应。
$model = Product::find($id);
$model->{$col} = $request->value;
try{
$model->save();
} catch (Exception $e){
return Response::json(['error' => $e->getMessage()], 500);
}
如果出现错误,它会返回以下响应代码 200,因此我在 ajax 中的错误处理不会触及这一点。我也无法在成功函数中处理它,因为它不是纯 json
HTTP/1.0 500 Internal Server Error
Cache-Control: no-cache, private
Content-Type: application/json
Date: Mon, 22 Jan 2018 16:06:17 GMT
{"error":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...."}
我发现在返回之前添加 http_response_code(500) 然后给我一个状态响应 500 但 responseText 仍然相同并且包含额外的文本而不仅仅是纯 json
我想要的回复应该是这样的
{"error":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...."}
这是我的 js ajax 代码
var post_data = {id:$(this.attr('id),value:$(this).value()}
$.ajax({
type:'POST',
data: post_data,
beforeSend:function(){
//stuff here to show user somethign is happening
},
success:function(returned_data){
console.log('successful!')
console.log(returned_data);
},
error:function(event, jqXHR, ajaxSettings, thrownError ) {
console.log('event');
console.log(event);
console.log('jqXHR');
console.log(jqXHR.responseText);
console.log('thrownError');
console.log(thrownError);
}
}
laravel 发送的文本看起来像标题,而不仅仅是纯 json,我做错了什么?
编辑:在尝试捕获之前添加代码
另外,我是故意造成这个错误的,所以我可以确保我的错误处理工作正常,但这不是因为我没有得到纯 json 并且它返回 200 响应代码
【问题讨论】:
-
上面是什么 ---->
try{ $model->save();?post_data包含什么? -
在
try catch和post data上面添加了代码。我故意造成错误以检查我的错误处理工作 -
我不确定这是否有帮助,但您可能想尝试使用这种格式
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);返回数据? -
仍然返回json数组上方的文本
HTTP/1.0 200 OK Cache-Control: no-cache, private Content-Type: application/json Date: Mon, 22 Jan 2018 18:50:13 GMT {"status":true}
标签: php ajax laravel-5.5