2012-07-12 18 views
1
$.ajax({ 
       type: "GET", 
       async: false, 
       url: "http://localhost:1234/api/", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       data: '{"id":"125"}', 
       success: function (data) { 
        console.log(data.toString()); 
       } 
      }); 

當我使用jQuery ajax調用API時,我傳遞的數據沒有很好地轉換爲查詢字符串參數。當使用jQuery ajax進行api請求時,數據不能很好地轉換爲查詢字符串參數

這是我看到的被稱爲。

http://localhost:1234/api/?{%22id%22:%22125%22} 

但是當我將數據作爲對象傳遞時,data:{「id」:「125」}工作正常。我在這裏做錯了什麼?

+1

使用'data:{「id」:「125」}'。 – 2012-07-12 19:28:06

+0

內容類型是應用程序/ JSON所以我不應該作爲JSON字符串傳遞?那麼爲什麼我應該指定內容類型? – user1186065 2012-07-12 19:30:40

+0

你已經指定了'contentType:'application/json'',這正是jQuery使用的:JSON。正如你所說的那樣。這就是你在查詢字符串中看到的:JSON。如果這不是你想要在你的查詢字符串中看到的,那麼不要告訴jQuery使用這個contentType。 – 2012-07-12 19:37:16

回答

0

因爲您指定了JSON數據類型,所以您將數據作爲js對象傳遞,並且jQuery將其轉換爲JSON格式。

$.ajax({ 
     type: "GET", 
     async: false, 
     url: "http://localhost:1234/api/", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     data: {"id": 125}, 
     success: function (data) { 
      console.log(data.toString()); 
     } 
    }); 
+0

我已經試過了,它爲我工作。但試圖理解爲什麼我必須作爲一個對象而不是JSON字符串傳遞,即使我的內容類型是json。 – user1186065 2012-07-13 14:50:39

+1

當您將內容類型設置爲JSON時,jQuery將您的對象轉換爲JSON,如果將其設置爲HTML,則可以傳遞字符串並且不會轉換。它更容易使用! – odupont 2012-07-14 08:45:08

相關問題