遇到关于javascript和JSON的错误

时间:2011-04-22 15:29:21

标签: javascript json

我正在学习JSON。我只是编写一个不起作用的简单代码,并且在单击按钮时也不会出现任何错误。所以请帮助我抓住错误。这是我的HTML。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" language="javascript">
        function GetJSON() 
        {
            alert("pp");

            var moviereviewtext = "{"title": "Friday the 13th", "year": 1980, "reviews": 
            [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"}, 
            {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}";
            var jsonobj = eval("(" + moviereviewtext + ")");

            var reviewername = jsonobj.reviews[0].reviewer;
            var numberstars = jsonobj.reviews[0].stars;
            var reviewerthoughts = jsonobj.reviews[0].text;

            alert(reviewername);
            alert(numberstars);
            alert(reviewerthoughts);
        }
    </script>
</head>
<body >
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetJSON();return false;" />
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

这取决于浏览器,但只有一些小改动:

// Use single quote to surround and line continuations to support new lines.
var movieReviewText = 
    '{"title": "Friday the 13th", "year": 1980, "reviews":\
    [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"},\ 
    {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}';

var obj = JSON.parse(movieReviewText); // This should be available IE8+, FF3+

另外,请注意,以大写字母开头的函数按照惯例被视为构造函数。函数的名称也可以更好,因为函数实际上并没有获得JSON。也许是这样的?

function parseMovieReview() {


}

答案 1 :(得分:1)

我认为问题出在ASP代码中。 尝试将ASP放在一边。以下代码适用于我:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript" language="javascript">
        function GetJSON() 
        {
            alert("pp");

            var moviereviewtext = '{"title": "Friday the 13th", "year": 1980, "reviews":\
            [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"},\
            {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}';
            var jsonobj = eval("(" + moviereviewtext + ")");

            var reviewername = jsonobj.reviews[0].reviewer;
            var numberstars = jsonobj.reviews[0].stars;
            var reviewerthoughts = jsonobj.reviews[0].text;

            alert(reviewername);
            alert(numberstars);
            alert(reviewerthoughts);
        }
    </script>
</head>
<body >
    <form id="form1">
        <Button ID="Button1" Text="Button" OnClick="GetJSON();return false;" />
    </form>
</body>
</html>