【问题标题】:JSON for loop through array shows only last valueJSON for 循环遍历数组仅显示最后一个值
【发布时间】:2018-01-06 19:02:58
【问题描述】:

我正在尝试使用 AXIOS 发出一个简单的 HTTP 发布请求。它就像一个 Ajax 请求来检索数据。这是HTML。它向 getData.php 发送一个 post 请求。

<!doctype html>
<html>
<head>
    <title>axios - post example</title>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
</head>
<body class="container">
<h1>Axios.post</h1>

<form role="form" class="form" onsubmit="return false;">
    <div class="form-group">
        <label for="data">Output</label>
        <textarea id="data" class="form-control container" rows="5"></textarea>
    </div>
    <button id="post" type="button" class="btn btn-primary">POST</button>
</form>

<!--<div id="output" class=""></div>-->

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    (function () {

        document.getElementById('post').onclick = function () {
            var output = document.getElementById('data');
            axios.post('getData.php')
                .then(function (res) {


                   // console.log(res.data);
                    output.className = 'container';
                        for (i = 0; i < res.data.length; i++) {
                        output.innerHTML = res.data[i].id + "\n" + res.data[i].name;

                    }

                })
                .catch(function (err) {
                    output.className = 'container text-danger';
                    output.innerHTML = err.message;
                });
        };
    })();
</script>
</body>
</html>`

在getData.php中

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = mysqli_connect($servername, $username, $password,"db_test");


$sql = "SELECT * FROM user";
$result = $conn->query($sql);
$resultArray = array();
if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $resultArray[] = $row;

    }

    echo json_encode($resultArray);
    return;

} else {
    echo "0 results";
}
$conn->close();

?>

但是当我试图循环遍历数组时,它只返回最后一行。它从表中获取数据并创建一个数组。 for 循环有什么问题?

【问题讨论】:

  • 不好,不连接output.innerHTML = 好是连接output.innerHTML +=

标签: php json axios


【解决方案1】:

output.innerHTML = res.data[i].id + "\n" + res.data[i].name;

只会替换之前添加的所有内容。

output.innerHTML += res.data[i].id + "\n" + res.data[i].name;

会解决你的问题。

【讨论】:

    【解决方案2】:

    因为你在for循环中覆盖了output.innerHTML所以last value只存在。

    使用appendChild()

    output.appendChild(res.data[i].id + "\n" + res.data[i].name);
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2014-05-25
      • 2013-12-26
      • 1970-01-01
      • 2017-03-31
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多