2014-04-19 68 views
1

我有这样的代码: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。

+0

这可能是您的JSON是无效的,可以肯定的检查[这里](http://jsonlint.com/) – Hatsjoem

+0

我已经检查过了,它与var hey中的json完全一样。 – bhc11

+0

请发布json。 – Hatsjoem

回答

1

尝试改变数据类型为JSON:

$.ajax({ 
    dataType: 'JSON', 
    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"); 
    } 
}); 
+0

如果您将dataType更改为JSON,则jQuery会为您解析它。所以不需要'var result = JSON.parse(data);'因为'data'已经是一个对象。但是,从其他评论看来,返回的JSONw是无效的。该方法需要服务器有效的JSON(和有效的JSON内容类型) – Adam

+0

是的,但是当我将它更改为json时,它给了我错误函数。我可能没有以正确的方式将json传递给服务器。 – bhc11

+0

您必须将标题内容类型设置为“text/json” – dbucki

4

在你的JSON的'角色使它成为一个JavaScript字符串,不形成数据的一部分。

它看起来像你在JSON中的那些字符,你通过HTTP请求,所以他们形成数据的一部分。

这不是有效的JSON。删除引号。

你应该有:

{"code": 123} 

'{"code": 123}'