javascript 未捕获的类型错误:无法读取未定义的属性“0”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5402080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property '0' of undefined
提问by ptamzz
I'm making an ajax call using jQuery as below.
我正在使用 jQuery 进行 ajax 调用,如下所示。
$.ajax({
type: "POST",
url: "proc.php",
dataType: 'json',
data: dataString,
cache: false,
success: function(data){
alert(data.vote[0].line); //Where error shows
}
});
The php page returns echo json_encode($string);
which is like
php页面返回echo json_encode($string);
就像
"{ 'vote' : [{ 'line' : 'newline1', 'up' : '0', 'down' : '1'},
{ 'line' : 'newline2', 'up' : '4', 'down' : '1'}
]}"
"{ 'vote' : [{ 'line' : 'newline1', 'up' : '0', 'down' : '1'},
{ 'line' : 'newline2', 'up' : '4', 'down' : '1'}
]}"
When I run it, an error comes up saying
当我运行它时,出现一个错误说
Uncaught TypeError: Cannot read property '0' of undefined
on the line commented above in the ajax call
Uncaught TypeError: Cannot read property '0' of undefined
在上面在 ajax 调用中评论的那一行
Can anyone help me point out where am I doing it wrong??
谁能帮我指出我哪里做错了??
UPDATE:
更新:
the variable $string
is generated as below
变量$string
生成如下
$comma = ",";
$success = mysql_query($query, $connection);
while($row = mysql_fetch_array($success)){
$voteUp = $row['voteup'];
$voteDwn = $row['votedwn'];
$vote .= $comma . "{ 'line' : '{$row['entryid']}', 'up' : '{$voteUp}', 'down' : '{$voteDwn}'";
$comma = ",";
}
$string = "{ 'vote' : [" . $vote . "]}";
echo json_encode($string);
回答by Thomas Menga
Instead of writing a "jsoned" string with PHP, use an array. json_encode()
will do the magic
不要用 PHP 编写“jsoned”字符串,而是使用数组。json_encode()
会变魔术
$return = array();
$success = mysql_query($query, $connection);
while ($row = mysql_fetch_array($success)) {
$return['vote'][] = array(
'line' => $row['entryid'],
'up' => $row['voteup'],
'down' => $row['votedown'],
);
}
echo json_encode($return);
回答by jordancpaul
In the recent releases of jQuery, native browser JSON parsing methods are used instead of the traditional eval() approach. Strict JSON does not support single quote strings, which your example is using. As previously mentioned, use json_encode($array) or fix your JSON manually
在 jQuery 的最新版本中,使用原生浏览器 JSON 解析方法代替传统的 eval() 方法。严格的 JSON不支持您的示例正在使用的单引号字符串。如前所述,使用 json_encode($array) 或手动修复您的 JSON