2011-04-22 54 views
0

我正在學習JSON。我只寫了一個簡單的代碼,它不起作用,點擊按鈕時也不會出現任何錯誤。所以請幫我抓住錯誤。這裏是我的HTML。關於javascript和JSON的遇到錯誤

<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> 

回答

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() { 


} 
+0

感謝您的努力,但沒有運氣.....仍然無法正常工作。 – Thomas 2011-04-22 15:51:12

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>