我有这样的代码:AJAX JSON意外的标记“
$.ajax({
dataType: 'text',
url: '/_/js/answers.json',
type: "GET",
success: function (data) {
alert(data);
alert(data.code);
var result = JSON.parse(data);
var hey = JSON.parse('{"code": 123}');
alert(hey.code);
alert(result.code);
},
error: function() {
alert("code not found");
}
});
在第一个警报,alert(data)
它让我看到 '{ ”代码“:123}',在第二个警报alert(data.code)
,它告诉我undefined
,在第三条提示alert(hey.code)
中,它显示我123
,这就是我想要的,但在第四条提示中,控制台告诉我Uncaught SyntaxError: Unexpected token '
。
当我改变JSON.parse
到$.parseJSON
,它完全一样的东西。
我不知道什么是错的,json很好(和var中的json完全一样)。
我通过JSON像这样的服务器: 的javascript:
var json = {code: code};
json = JSON.stringify(json);
json = {data: json};
$.ajax({
url: "/_/js/write-json.php",
type: "POST",
dataType: 'json',
data: json
});
PHP:
<?php
$myFile = "answers.json";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh,var_export($_POST['data'], true));
fclose($fh);
?>
谢谢,bhc11。
这可能是您的JSON是无效的,可以肯定的检查[这里](http://jsonlint.com/) – Hatsjoem
我已经检查过了,它与var hey中的json完全一样。 – bhc11
请发布json。 – Hatsjoem