我正在嘗試根據我作為測驗收到的模板創建一個 JavaScript 物件。我使用 Ajax 從我的資料庫中獲取資料,但我似乎無法創建物件。
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'fetch.php',
dataType: 'JSON',
success: function(response) {
var test = JSON.parse(response);
var products = {};
for (var x = 0; x < test.length; x ) {
products[x] = {
productName: test[x]['name']
};
products[x] = {
category: test[x]['category']
};
products[x] = {
price: test[x]['price']
};
}
}
});
});
我正在嘗試在下面創建類似這個物件的東西
products = {data: [
{
productName: "test_item_1",
category: "category1",
price: "49",
image: "test_image.jpg",
},
{
productName: "test_item_2",
category: "category3",
price: "99",
image: "test_image.jpg",
},
{
productName: "test_item_3",
category: "category3",
price: "29",
image: "test_image.jpg",
},],};
這就是我從資料庫中獲取資料的方式
while($row = mysqli_fetch_assoc($run)){$datas[] = $row;}echo json_encode($datas);
uj5u.com熱心網友回復:
你的行用products[x]覆寫前面的。
改成
products[x] = {
productName: test[x]['name'],
category: test[x]['category'],
price: test[x]['price'],
};
uj5u.com熱心網友回復:
首先有幾個問題...
- 配置
$.ajax()選項是dataType,不是datatype - 指定
dataType: "json"意味著 jQuery 將自動將回應決議為 JSON。您無需再次手動決議
至于您的映射問題,您可以將回應陣列映射到一個新的并重name命名為productName使用Array.prototype.map()
$.ajax("fetch.php", {
method: "POST",
dataType: "json",
// data: ˉ\_(ツ)_/ˉ
}).done(data => {
const products = {
data: data.map(({ name: productName, category, price }) => ({
productName,
category,
price
}))
};
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439723.html
標籤:javascript php jQuery 阿贾克斯
