简体   繁体   English

使用Javascript以HTML显示来自AJAX的多行数组

[英]Displaying multi-row array from AJAX in HTML with Javascript

I'm building a mobile app through Cordova and I'm having trouble displaying an array I'm using to get data from a database through AJAX. 我正在通过Cordova构建移动应用程序,但无法显示用于通过AJAX从数据库获取数据的数组。 I've gotten the php working to produce what I think is a properly formatted array but it is getting mangled and turned into "object, object" somewhere along the line. 我已经使php能够产生我认为是正确格式的数组,但是它正被整顿并沿直线某处变成“对象,对象”。

I'm also not massively sure on actually putting that data into the html since it's my first time doing this in javascript (would normally just use php), but that is less important than getting the bloody data across properly. 我也不是很确定将这些数据真正放入html中,因为这是我第一次在javascript中进行此操作(通常只会使用php),但这并不如正确地获取流血数据重要。

HTML/Javascript: HTML / Javascript:

<body onload="getList();">
<div class="app">

<div id="output">If you can see this text something has gone wrong. </div>

<script language="javascript" type="text/javascript">
function getList(){

    $.ajax({
        url: "***.php",
        data: "",
        dataType: 'json',
        success: function(data)
        {
            alert("unparsed data"+data);
            data = JSON.parse(data);
            alert("parsed data"+data);

            for (var x = 0; x < data.length; x++) {
                content = data[x].PID;
                content += "<br>";
                content += data[x].name;
                content += "<br>";
                $("#output").append(content);
            }
        },
        error: function(jqXHR, textStatus)
        {
            alert( "Request failed: " + textStatus );
        }
    });
};
</script>
</div>

The the php file producing the array is 产生数组的php文件是

$results_array = array();
$results = mysqli_query($db_server, $query); 

while($row = mysqli_fetch_row($results)){
$table_data[]= array("PID"=>$row[1],"name"=>$row[3]);
}
echo json_encode($table_data);

Which when run in browser produces 在浏览器中运行时会产生

[{"PID":"11","name":"testname"},{"PID":"11","name":"Dev2test"}]

But when I run the actual app, the first alert inside the ajax success function returns 但是,当我运行实际的应用程序时,ajax成功函数中的第一个警报将返回

"unparsed data[object Object],[object Object]"

But then the second alert doesn't fire, and nothing is appended to the html. 但是,第二个警报不会触发,并且HTML不会附加任何内容。

Because you are specifying dataType: 'json' in your query the returned response will already be parsed as JSON and so you don't need to use JSON.parse . 因为您在查询中指定了dataType: 'json' ,所以返回的响应已经被解析为JSON,因此您不需要使用JSON.parse

It is not reaching the second alert as I imagine JSON.parse(data) is emitting an error due to data already being an object. 由于我想像JSON.parse(data)正在发出错误,因为数据已经是一个对象,所以它没有达到第二个警报。

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

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