将 PHP 数组从 AJAX 响应转换为 Javascript 对象

Convert PHP array from AJAX response to Javascript Object

我正在尝试根据我作为测试收到的模板创建一个 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);

您的 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()

将响应数组映射到一个 name 重命名为 productName 的新数组
$.ajax("fetch.php", {
  method: "POST",
  dataType: "json",
  // data: ¯\_(ツ)_/¯
}).done(data => {
  const products = {
    data: data.map(({ name: productName, category, price }) => ({
      productName,
      category,
      price
    }))
  };
});