【问题标题】:How can I get content from php array to js array?如何从 php 数组获取内容到 js 数组?
【发布时间】:2021-04-25 20:16:56
【问题描述】:

我在将 php 数组转换为 js 数组时遇到问题。这是我的代码:

    <?php
session_start();
require "db.inc.php";

$id = $_SESSION['id'];
$stmt = $pdo->prepare("SELECT `pixels`, `status` FROM datagame WHERE `id_user`='$id'");
$stmt->execute();

$result_array = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($result_array);

还有 JS:

let arr = [];
$(document).ready(function () {
  $.ajax({
    type: "POST",
    url: "includes/test.inc.php",
  })
    .done(function (data) {
      arr = JSON.parse(data);
  i=0;
  while (i<=Object.keys(arr).length) {
    alert(arr.pixels[i]);
    i++;
  }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
      alert(textStatus);
    });
});

而且它正在工作和不工作。我有这个错误:

未捕获的类型错误:无法读取未定义的属性“0” 我能做什么?

【问题讨论】:

  • 错误信息告诉arr.pixels不存在。 console.log(arr)解析后,你会看到你从服务器得到了什么。
  • 我得到了这个:(3) [{...}, {...}, {...}, {...}, {...}, {...}] 0:像素:“pix39”状态:“ 1" proto:对象 1:{像素:“pix60”,状态:“1”} 2:{像素:“pix98”,状态:“1”} 长度:3 proto:数组(0)
  • 请将日志结果添加到帖子中,并将其格式化为代码,这样会更清楚。
  • 现在有了数据,我们可以看到,你有一个对象数组。代替while 循环,执行arr.forEach(function (obj) {alert(obj.pixels);});。您还可以将数据代码添加到问题本身,并删除答案。答案是为了……嗯……答案而已。

标签: javascript php jquery json ajax


【解决方案1】:
let arr = [];
$(document).ready(function () {
  $.ajax({
    type: "POST",
    url: "includes/test.inc.php",
  })
    .done(function (data) {
      arr = JSON.parse(data);
      console.log(arr);
      arr.forEach(function (obj) {
        alert(obj.pixels);
      });
      
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
      alert(textStatus);
    });
});

forEach 它没有更多错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 2019-09-24
    • 2019-10-23
    • 2015-03-20
    相关资源
    最近更新 更多