如何解决W3 JS解析Spring Boot RESTful API返回JSON的报错
解决W3.JS中
w3-repeat的数组类型错误问题 你遇到的报错原因很明确:W3.JS的w3-repeat指令要求迭代的目标必须是数组,但你的JSON结构里,每个客户的orders是一个对象,真正的订单数组藏在orders.order这个属性里,直接循环c.orders自然会触发类型错误。
另外还有个容易忽略的小问题:你HTML里写的ShipCountry字段名大小写和JSON里的shipCountry不一致,不改的话这列内容会显示为空。
具体修复步骤:
- 修正循环目标:把嵌套表格里的
w3-repeat="o in c.orders"改成w3-repeat="o in c.orders.order",这样就指向了真正的订单数组。 - 修正字段名大小写:把
<td>{{o.ShipCountry}}</td>改成<td>{{o.shipCountry}}</td>,和JSON里的字段名保持严格一致。
修复后的完整HTML代码:
<!DOCTYPE html> <html> <title>W3.JS</title> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://www.w3schools.com/lib/w3.js"></script> <body class="w3-container"> <table id="id01" class="w3-table-all"> <tr> <th>Customer Id</th> <th>Name</th> <th>Country</th> <th>Orders</th> </tr> <tbody w3-repeat="c in customers"> <tr> <td>{{c.customerId}}</td> <td>{{c.name}}</td> <td>{{c.country}}</td> <td> <table class="w3-table-all"> <tr> <th>Order Id</th> <th>Freight</th> <th>ShipCountry</th> </tr> <tbody w3-repeat="o in c.orders.order"> <tr> <td>{{o.orderId}}</td> <td>{{o.freight}}</td> <td>{{o.shipCountry}}</td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <script> w3.getHttpObject('http://localhost:8080/customers/all', myFunction); function myFunction(myObject) { w3.displayObject("id01", myObject); } </script> </body> </html>
修改后,w3-repeat会正确遍历每个客户订单对象里的order数组,同时字段名匹配JSON结构,数据就能正常渲染到页面上了。
内容的提问来源于stack exchange,提问作者user12563258




