簡體   English   中英

將 PHP 數組從 AJAX 響應轉換為 Javascript Object

[英]Convert PHP array from AJAX response to Javascript Object

我正在嘗試根據我作為測試收到的模板創建一個 JavaScript object。 我使用 Ajax 從我的數據庫中獲取數據,但我似乎無法創建 object。

$(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']
        };
      }
    }
  });
});

我正在嘗試在下面創建類似 object 的內容

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);

您帶有products[x]的行會覆蓋較早的行。

改成

                  products[x] = {
                      productName: test[x]['name'],
                      category: test[x]['category'],
                      price: test[x]['price'],
                  };

首先有幾個問題...

  1. $.ajax()配置選項是dataType ,而不是datatype
  2. 指定dataType: "json"表示jQuery會自動將響應解析為JSON,不需要再手動解析

至於您的映射問題,您可以使用Array.prototype.map()將響應數組 map 更改為name重命名為productName的新數組

$.ajax("fetch.php", {
  method: "POST",
  dataType: "json",
  // data: ¯\_(ツ)_/¯
}).done(data => {
  const products = {
    data: data.map(({ name: productName, category, price }) => ({
      productName,
      category,
      price
    }))
  };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM