2011-12-05 72 views
1

我有下面的html,警告只在Mozilla Firefox中有效,當我點擊按鈕時。爲什麼?jquery ajax請求只適用於firefox

<html> 
     <head> 
     <script type="text/javascript" src="jquery.js"></script> 
     <script type="text/javascript"> 
     $(document).ready(function(){ 
     $("button").click(function(){ 
      $.ajax({url:"https://graph.facebook.com/1524623057/", 
      success:function(){ 
      alert(1); 
      }}); 
     });}); 
     </script> 
     </head> 
     <body> 

     <button>send request</button> 
     </body> 
     </html> 
+0

[jquery的ajax不能在facebook應用中工作]的可能副本(http://stackoverflow.com/questions/1186855/jquerys-ajax-not-working-in-facebook-apps) – Jasper

回答

2

來自Facebook的結果是不正確的JSON,因爲它換行和標籤 - 此外,它是爲text/JavaScript的。

Facebook的支持JSONP,但是,這樣你就可以這樣做,而不是:

$.ajax({ 
    url: 'https://graph.facebook.com/1524623057/', 
    type: 'get', 
    dataType: 'jsonp' 
}).done(function(data){ 
    // the data! 
}); 

這將在回調= jQuery23423234234或者其他基本上不粘隨機ID生成給Facebook,返回一個可以調用的函數。

如果你想自己解析它,這樣做:

告訴$.ajax使用類型「文本」,例如

$.ajax({ 
    url: 'https://graph.facebook.com/1524623057/', 
    dataType: 'text' 
}) 

然後清理它。這裏是關於清理那種js的一個答案,所以你可以使用$.parseJSON,而不必把它放在一個新的函數中或評估它。 Converting multiline, indented json to single line using javascript

這樣,你可以var data = $.parseJSON(cleanedUpJsonFromFacebook)並訪問對象的屬性。

2

它看起來像那個請求返回一個JSON數據類型。該代碼在接收結果並且無法識別JSON時抱怨冒號。

試試這個:

$.ajax("https://graph.facebook.com/1524623057/", 
    { 
     success:function(){ 
      alert(1); 
     }, 
     dataType: 'json' 
    } 
); 

此外,成功回調需要,你可以用,當你回檢查JSON的響應參數。

退房http://api.jquery.com/jQuery.ajax/

+1

從fb返回的數據isn' t有效的json,無論是在類型(文本/ JavaScript)和格式(有效的json不包含新的行或標籤字符之間的鍵和值) –

+1

有用的信息。另一個不喜歡FB的原因... –

+0

我覺得他們的腳本會做'var result =(new Function('return'+ data)());'' –