可以吗?在非 HTTP-200 响应中返回 HTML 标记?

发布于 2024-11-05 07:19:20 字数 505 浏览 3 评论 0原文

想象一下,页面上有一个表单,并且您以 AJAXian 方式(例如 jQuery.post())将该表单的数据 POST 到服务器。服务器判断数据无效,因为例如电子邮件地址不包含“@”符号。

我认为 HTTP 的精神是服务器应该返回“HTTP 400 Bad Request”状态代码及其响应,以向客户端表明它无法处理该请求。原因(数据未验证)应位于响应正文中。

但我在 ASP.NET MVC 环境中工作,该环境传统上实现了“部分视图”——作为响应发送的 HTML 片段,意味着在从 AJAX 请求接收时将其替换到客户端的 DOM 中。在此范例中,服务器通常构建表单的替代版本,填充(无效)提交的值,并使用红色突出显示和警报来表示电子邮件地址无效并应更正。客户端将该表单替换到其 DOM 中,然后用户就会看到问题。

这是 MVC 世界中很常见的模式,但我没有看到有人注意设置适当的 HTTP 状态代码。我不明白为什么。

在非 HTTP-200 响应中包含 HTML 标记以便客户端可以显示验证是否“可以”?我找不到任何说不是的东西。

Imagine you've got a form on a page, and you POST that form's data to the server in an AJAXian way, e.g. jQuery.post(). The server judges that the data is invalid because, say, the email address doesn't contain an '@' symbol.

I think that the spirit of HTTP says the server should return an "HTTP 400 Bad Request" status code with its response to indicate to the client that it couldn't process the request. The reason (data didn't validate) should be in the body of the response.

But I'm working in an ASP.NET MVC environment that has traditionally implemented "partial views"--HTML fragments sent as responses, meant to be substituted into the client's DOM when received from an AJAX request. In this paradigm, the server typically constructs an alternative version of the form, filled with the (invalid) submitted values and styled with red highlights and alerts indicating that the email address was invalid and should be corrected. The client substitutes that form into its DOM, and the user sees the problem.

This is a common enough pattern in MVC world, but I don't see anybody taking the care to set an appropriate HTTP status code. I can't figure out why.

Is it "okay" to include HTML markup in a non-HTTP-200 response so that the client can show a validation? I can't find anything that says it isn't.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

镜花水月 2024-11-12 07:19:20

取决于返回的状态代码以及您打算如何使用它,但通常可以。

Depends on the status code being returned and how you intend to use it, but generally you can.

很酷又爱笑 2024-11-12 07:19:20

如果您知道可以解析响应,请发送一个 json/xml 文档,其中包含正确的 mime 类型和信息。否则只需发送人类可读的 HTML 内容。在这两种情况下,显然都设置了正确的 HTTP 状态代码。

If you know that the response could be parsed, send a json/xml document with the right mime type and informations inside. Else just send a human readable HTML content. In both cases obviously set the right HTTP status code.

余厌 2024-11-12 07:19:20

我认为如果机器收到响应,发送 HTML 是没有意义的。

但如果您正在构建的内容具有用户交互(例如通过浏览器),那么当然可以。

输入图片此处描述

I suppose it doesn't make sense to send HTML if a machine is getting the response.

But if what you're building has user interaction (e.g. via a browser), then sure.

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文