从 @RestContoller 使用 JavaScript 获取 JSON 数据

huangapple go评论55阅读模式
英文:

Fetching JSON data from @RestContoller using JavaScript

问题

The HTML页面为何无法加载特定请求的URL并无法从JSON格式中获取数据的问题?

控制器(Controller)代码部分:

@RestController
@RequestMapping("api/reservations")
public class ReservationController {

    private final ReservationService reservationService;

    @Autowired
    public ReservationController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }

    @GetMapping("/all")
    public List<Reservation> showAllReservations() throws SQLException {
        return reservationService.showAllReservations();
    }
}

HTML + JavaScript部分:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Reservations</title>
  </head>
  <body>
    <script>
      // 从REST控制器获取JSON数据
      fetch("http://localhost:8080/api/reservations/all")
        .then((response) => response.json())
        .then((data) => {
          // 遍历JSON数组中的每个对象
          var formattedData = "";

          data.forEach((item) => {
            formattedData +=
              "<p>Reservation ID: " +
              item.id +
              "</p>" +
              "<p>Customer: " +
              item.customer.name +
              "</p>" +
              "<p>Email: " +
              item.customer.email +
              "</p>" +
              "<p>Check-in Date: " +
              item.dateCheckIn +
              "</p>" +
              "<p>Check-out Date: " +
              item.dateCheckOut +
              "</p>" +
              "<hr>";
          });
          // 使用格式化数据更新HTML容器
          var dataContainer = document.getElementById("data-container");
          dataContainer.innerHTML = formattedData;
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    </script>
    <div id="data-container"></div>
  </body>
</html>

您已经检查了URL的正确性,控制器看起来也没问题,文件位于不同的文件夹中(模板用于.html文件,src>java>package用于控制器)。

英文:

Why the html page doesn't load on specific requested URL and doesn't fetching data from JSON format?
Result of opening api/reservations/all

Controller:

@RestController
@RequestMapping(&quot;api/reservations&quot;)
public class ReservationController {

    private final ReservationService reservationService;

    @Autowired
    public ReservationController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }
 @GetMapping(&quot;/all&quot;)
    public List&lt;Reservation&gt; showAllReservations() throws SQLException {
        return reservationService.showAllReservations();
    }
}

HTML + Javascript

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
    &lt;title&gt;Reservations&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;script&gt;
      // Fetch JSON data from REST controller
      fetch(&quot;http://localhost:8080/api/reservations/all&quot;)
        .then((response) =&gt; response.json())
        .then((data) =&gt; {
          // Iterate over each object in the JSON array
          var formattedData = &quot;&quot;;

          data.forEach((item) =&gt; {
            formattedData +=
              &quot;&lt;p&gt;Reservation ID: &quot; +
              item.id +
              &quot;&lt;/p&gt;&quot; +
              &quot;&lt;p&gt;Customer: &quot; +
              item.customer.name +
              &quot;&lt;/p&gt;&quot; +
              &quot;&lt;p&gt;Email: &quot; +
              item.customer.email +
              &quot;&lt;/p&gt;&quot; +
              &quot;&lt;p&gt;Check-in Date: &quot; +
              item.dateCheckIn +
              &quot;&lt;/p&gt;&quot; +
              &quot;&lt;p&gt;Check-out Date: &quot; +
              item.dateCheckOut +
              &quot;&lt;/p&gt;&quot; +
              &quot;&lt;hr&gt;&quot;; 
          });
          // Update the HTML container with the formatted data
          var dataContainer = document.getElementById(&quot;data-container&quot;);
          dataContainer.innerHTML = formattedData;
        })
        .catch((error) =&gt; {
          console.error(&quot;Error:&quot;, error);
        });
    &lt;/script&gt;
    &lt;div id=&quot;data-container&quot;&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;

I checked URL correctness, controller seems fine, the files locates in different folders (templates for .html and src>java>package for controller).

答案1

得分: 0

问题出在粗心大意上,点击按钮将我带到了api/reservation/all而不是reservations.html,所以JavaScript无法运行,也无法显示结果。感谢你的答案。

英文:

The problem was inattention, clicking on the button took me to api/reservation/all instead of reservations.html and so the javascript didn't work and didn't show the result. Thanks for your answers.

huangapple
  • 本文由 发表于 2023年5月23日 01:50:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定