javascript 如何使用HTMX交换DOM中的响应,当它是4xx或5xx响应HTTP状态码时?

q9rjltbz  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(98)

我正在尝试使用HTMX做下一个:

<form hx-boost="true" hx-target="#response" hx-swap="afterbegin">
    <label for="title">Title of your post</label>
    <input type="text" id="title" name="title">
    <button type="submit">Send post</button>
</form>
<div id="response">
    <!-- Here goes the response from the server -->
</div>

在服务器中,内部逻辑是:
当文章的标题为空时,返回一些div,其中包含一条消息,指示请求中的错误,并以400 HTTP状态代码进行响应,但当我这样做时,响应并没有被交换(当然,如果HTTP状态为200,则来自服务器的任何内容都会被交换)。
我尝试了一些奇怪的东西,如果你在浏览器中禁用JavaScript,页面会完全重新加载并正确加载div。
这不是Content-Type标头错误,因为服务器响应时CT标头为text/html; charset=utf-8

idv4meu8

idv4meu81#

  1. HTMX需要额外的脚本来处理错误响应,您可以添加此<script src='https://unpkg.com/htmx.org/dist/ext/response-targets.js'></script>,沿着您的HTMX脚本。
    1.必须使用属性hx-ext=“response-targets” Package 外部元素。
    1.使用hx-target-4xxhx-target-5xx属性处理错误响应。
    如果你的代码是这样的话,你的代码应该是可以工作的:
<div hx-ext='response-targets'>
  <form hx-boost="true" hx-target="#response" hx-target-4xx='#errorResponse' hx-swap="afterbegin">
      <label for="title">Title of your post</label>
      <input type="text" id="title" name="title">
      <button type="submit">Send post</button>
  </form>
  <div id="response">
      <!-- Here goes the response from the server -->
  </div>
  <div id="errorResponse">
      <!-- Here goes the error response from the server -->
  </div>
</div>

相关问题