简体   繁体   English

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

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

I have a simple website here. 我这里有一个简单的网站。 It contains a div item with a css object inside. 它包含一个div项目,里面有一个css对象。 I'm trying to use ajax and json to run a php script that will grab a value out of a text file and update the div item with said value. 我正在尝试使用ajaxjson运行一个php脚本,该脚本将从文本文件中获取值并使用所述值更新div项。

Problem is passing dataList[0] to a the function replaceContentInContainer() comes up as an undefined error in console. 问题是将dataList[0]传递给函数replaceContentInContainer()在控制台中出现为未定义的错误。

Here is the script that is throwing the error. 这是抛出错误的脚本。 It throws it as soon as dataList[0] is referenced. 一引用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>

the PHP file PHP文件

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

Data File format 'data.txt' 数据文件格式'data.txt'

78\n
82\n
33\n 
etc...

Console output as follows 控制台输出如下

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

It doesnt make sense why it thinks my array is undefined or at least why I am not allowed to define the element by a index. 它没有意义为什么它认为我的数组是未定义的,或者至少为什么我不允许通过索引定义元素。

dataList = data.value; should be dataList = data; 应该是dataList = data; as you're not returning an object, so there is no value property. 因为你没有返回一个对象,所以没有value属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM