未定义的数组错误(javascript)使用php/ajax/json等


Undefined array error (javascript) using php/ajax/json etc

我这里有一个简单的网站。它包含一个div项,里面有一个css对象。我正在尝试使用 ajaxjson 来运行一个php脚本,该脚本将从文本文件中获取一个值并使用该值更新div 项。

问题正在将dataList[0]传递给函数replaceContentInContainer()该函数在控制台中显示为未定义的错误。

这是引发错误的脚本。 一旦引用dataList[0],它就会抛出它。

<script>
    setInterval(function()
    {
        $.getJSON('loadData.php', function(data){
            var dataList = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
            dataList = data.value;
            var tempID = "tempDIV";
            console.log('Good to go, data was loaded');
            console.log(data);
            ReplaceContentInContainer(tempID,dataList[0]);
        }
    }, 2000);
    </script>
    <script type="text/javascript"><!--
        function ReplaceContentInContainer(id,content) {
        var container = document.getElementById(id);
        container.innerHTML = content;
    }
    //--></script>

PHP 文件

<?php
    $lines = file("data.txt");
    echo json_encode($lines);
?>
数据

文件格式"数据.txt"

78'n
82'n
33'n 
etc...

控制台输出如下

Good to go, data was loaded indexUpdate.php:30:5
Array [ "75 ", "34 ", "0 ", "0 ", "80 ", "31 ", "60 ", "72 ", "60 ", "70 ", 8 more… ] indexUpdate.php:31:5
TypeError: dataList is undefined
 indexUpdate.php:32:5
Good to go, data was loaded indexUpdate.php:30:5
Array [ "75 ", "34 ", "0 ", "0 ", "80 ", "31 ", "60 ", "72 ", "60 ", "70 ", 8 more… ] indexUpdate.php:31:5
TypeError: dataList is undefined

为什么它认为我的数组是未定义的,或者至少为什么不允许我通过索引定义元素,这是没有意义的。

dataList = data.value;应该dataList = data;,因为您不返回对象,因此没有value属性。