简体   繁体   English

返回正确的JSON响应

[英]Returning a correct JSON response

I'm using Laravel 4 for a project I'm working on. 我正在使用Laravel 4进行我正在进行的项目。 It relies heavily on AJAX for a lot of its functionality. 它在很多功能上都非常依赖AJAX。

In the jQuery I use to upload files (fileupload), I have the following success and fail function: 在jQuery我用来上传文件(fileupload),我有以下成功和失败的功能:

done: function (e, data) {
    // Show success message
},
fail: function (e, data) {
    // Show fail message
}

In my controller, I use the following to return success or fail: 在我的控制器中,我使用以下命令返回成功或失败:

// Success Response
return Response::json('success', 200)

// Fail Response
return Response::json('error', 400)

Everything works fine with the functionality, the success and fail messages show up, the file uploads, everything is perfect, except when the function fails and it returns the fail response, in the console I see: 一切正常,功能,成功和失败消息显示,文件上传,一切都很完美,除非功能失败并返回失败响应,在控制台中我看到:

400 (Bad Request)

The error message still shows and its all good, but I'm just wondering if I'm handling this correctly, I don't like red errors showing in my console for something that seems to be working correct. 错误消息仍然显示并且一切都很好,但我只是想知道我是否正确处理此问题,我不喜欢在我的控制台中显示的红色错误似乎正常工作。

Any advice would be greatly appreciated. 任何建议将不胜感激。

That is exactly how it works. 这正是它的工作原理。 You are throwing a HTML Status Code for an error - which is a 'best practice' for an API. 您正在为错误抛出HTML状态代码 - 这是API的“最佳实践”。

The console is showing an error, because it sees a non-200 status code, and then alerts you. 控制台显示错误,因为它看到非200状态代码,然后提醒您。

For API, if there is an error, I often use 500 code because it is an server error. 对于API,如果出现错误,我经常使用500代码,因为它是服务器错误。 40x code is used with client errors as mentioned in this document http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 如本文档中所述, 40x代码与客户端错误一起使用http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

In your case, 400 code let browser think that your API endpoint does not exist when 500 code tell it that that endpoint is OK but there is an error when manipulating your call. 在您的情况下,400代码让浏览器认为您的API端点不存在,当500代码告诉它该端点是正常但操作您的调用时出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM