我開始學習 alpine js 結合順風。但我不知道如何從 json 回應中列印獲取結果,試試這個
<div x-data="orderSearch()"
class="container mx-auto py-6 px-4"
>
<div >
<input type="text" placeholder="Search" name="orderidSearch"
x-model="orderidSearch">
<button @click="fetchFulfillment()" >Cari Fulfillment</button>
但在控制臺 alpine.js:115 Alpine 錯誤中回傳錯誤:“TypeError: Cannot read properties of undefined (reading 'inv_id')”
有人知道如何在 div 中列印結果嗎?
我的js函式:
function orderSearch() {
return {
orderidSearch: '',
// other default properties
orders: [],
fetchOrders() {
this.isLoading = true;
fetch(`check.php?order_id=${this.orderidSearch}`)
.then(res => res.json())
.then(data => {
this.isLoading = false;
this.orders = data.orders;
console.log(data);
});
console.log(this.orders);
},
....
json 回傳資料:
{"data":[{"inv_id":"8768768768"]}
uj5u.com熱心網友回復:
出現問題是因為您將獲得一個可迭代的物件。我稍微重寫了您的代碼并將函式行內以顯示第一個條目。如果你有一個集合,然后建立你的回圈來播種每個專案。
<div
class="container mx-auto py-6 px-4"
x-data="{
orders: null,
isLoading: false,
orderSearch() {
this.isLoading = true;
fetch(`check.php?order_id=${this.orderidSearch}`)
.then((response) => response.json())
.then((json) => this.orders = json);
}
}" x-init="orderSearch()">
<p x-text="orders[0].inv_id"></p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466441.html
標籤:javascript 获取 API alpine.js
