繁体   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