2012-02-13 149 views
10

我使用jQuery AJAX使得這個簡單的GET請求:AJAX的jQuery簡單的GET請求

 $.ajax({ 
      url: "https://app.asana.com/-/api/0.1/workspaces/", 
      type: 'GET', 
      success: function(res) { 
       console.log(res); 
       alert(res); 
      } 
     }); 

它返回一個空字符串作爲結果。如果我去我的瀏覽器這個環節,我得到:

{"status":401,"error":"Not Authorized"} 

這是預期的結果。那爲什麼它不使用ajax? 謝謝!

+1

你嘗試過將數據類型:在那裏 – 2012-02-13 22:55:44

+0

@KaiQing 「JSONP」,這ISN這裏根本就沒有問題。否則,成功處理程序將不會被調用。此外,示例響應不是JSONP響應。 – Brad 2012-02-13 22:57:29

+0

@PragmaOnce,用Wireshark等數據包檢查你的頭文件。我懷疑你會發現從瀏覽器發送的內容和AJAX調用之間的區別。 – Brad 2012-02-13 22:58:39

回答

6

在我看來,這是一個跨領域的問題,因爲你不能使請求到不同的域。

你必須爲這個問題的解決方案: - 使用代理腳本,在服務器上運行,將轉寄您的請求,將處理它發送到瀏覽器 或者 的反應 - 你正在做請求應該服務有JSONP支持。這是一個跨域技術。您可能想要閱讀這個http://en.wikipedia.org/wiki/JSONP

1

您可以對從同一域和同一端口加載的應用程序發出AJAX請求。

除此之外,如果您希望自動對結果進行反序列化,則應該添加dataType JSON

$.ajax({ 
     url: "https://app.asana.com/-/api/0.1/workspaces/", 
     type: 'GET', 
     dataType: 'json', // added data type 
     success: function(res) { 
      console.log(res); 
      alert(res); 
     } 
    }); 

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

1

我認爲問題是成功函數中沒有數據,因爲請求在您的情況下發生了401錯誤,因此沒有成功。

如果使用

$.ajax({ 
     url: "https://app.asana.com/-/api/0.1/workspaces/", 
     type: 'GET', 
     error: function (xhr, ajaxOptions, thrownError) { 
    alert(xhr.status); 
    alert(thrownError); 
    } 
    }); 

會有你的401碼,我認爲(this link是這麼說的)

2
var dataString = "flag=fetchmediaaudio&id="+id; 

$.ajax 
({ 
    type: "POST", 
    url: "ajax.php", 
    data: dataString, 
    success: function(html) 
    { 
    alert(html); 
    } 
});