【发布时间】:2016-01-09 08:12:51
【问题描述】:
我使用 Yii 框架编写网站。我需要从 Yii 中的数据库中获取所有数据,为此我编写了一些代码:
var response =
<?php
function getAllDataTable() {
$connection = Yii::app()->db;
$sql = "SELECT * FROM data";
$command = $connection->createCommand($sql);
$rows = $command->queryAll();
return $rows;
}
function getJsonFromRows($rows) {
$json = "{ ";
foreach ($rows as $rowIndex => $rowData) {
if ($rowIndex !== 0)
$json .= ", ";
$json .= "\"row".$rowIndex."\": {";
$colIndex = 0;
foreach ($rowData as $columnHeader => $cellValue) {
if ($colIndex++ !== 0)
$json .= ", ";
$json .= "\"".$columnHeader."\"".": "."\"".$cellValue."\"";
}
$json .= "} ";
}
$json.="}";
return $json;
}
$rows = getAllDataTable();
echo getJsonFromRows($rows);
?>;
var data = JSON.parse(response);
console.log("data: \"" + data + "\"");
我尝试使用 JSON 来做到这一点。 这是来自调试器的代码:
var response = { "row0": {"year": "2001", "discipline": "some discipline", "theme": "some theme", "pair": "some pair"} , "row1": {"year": "2001", "discipline": "some discipline", "theme": "some theme", "pair": "some pair"} };
var data = JSON.parse(response);
console.log("data: \"" + data + "\"");
这是我得到的错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data material:53:18
Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery-1.9.1.min.js:1:0
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
我在许多网站上检查 php 脚本的结果,例如: https://jsonformatter.curiousconcept.com/ 我的 json 对象是正确的,但 JSON.parse(jsonObject) 返回错误。为什么?
附:这个主题不是重复的,我看到了所有这些帖子: JSON Lint says it's valid but JSON.parse throws error jQuery IE9 JSON.SyntaxError parseerror, but JSON is valid JSON.parse Error on Valid JSON check if required JSON is valid - node JSON.parse error on a seemingly valid JSON
【问题讨论】:
-
有效或无效。 JSON Lint 真的 说它是有效的,然后你使用不同的数据。回到(并纠正)假设:JSON 是文本。在显示的代码中,没有 JSON,而是分配了一个 JavaScript 对象字面量。
-
另外,不要手动创建 JSON/XML/等。至少在某些时候或使用某些数据,您肯定会弄错。
标签: javascript php json yii