2014-12-04 79 views
0

我想在使用Intel XDK開發的跨平臺應用程序中使用Google Url Shortener API。至少在仿真器中,似乎沒有強制實施SOP。 無論如何,我得到這樣的迴應:Intel XDK Google API JQuery

{"readyState":4,"responseText":"{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"global\",\n \"reason\": \"required\",\n \"message\": \"Required parameter: shortUrl\",\n \"locationType\": \"parameter\",\n \"location\": \"shortUrl\"\n }\n ],\n \"code\": 400,\n \"message\": \"Required parameter: shortUrl\"\n }\n}\n","responseJSON":{"error":{"errors":[{"domain":"global","reason":"required","message":"Required parameter: shortUrl","locationType":"parameter","location":"shortUrl"}],"code":400,"message":"Required parameter: shortUrl"}},"status":400,"statusText":"Bad Request" 

代碼:

$.ajax(
    { 
     url: "https://www.googleapis.com/urlshortener/v1/url", 
     contentType: "application/json", 
     data: { longUrl: "firec.at" }, 
     success: function (data) { 
       $("#txtUsernameLogin").val(JSON.stringify(data)); 
     }, 
     error: function(data) 
     { 
      $("#txtUsernameLogin").val(JSON.stringify(data)); 
     } 
    }); 

看起來像它不發送longUrl PARAM。我不知道爲什麼會失敗,並感謝任何建議。謝謝。

回答

1

因爲jQuery不會自動轉換JSON字符串中的對象。您可以使用JSON.stringify

data: JSON.stringify({ longUrl: "firec.at" }), 

注意JSON.stringify並不適用於所有的瀏覽器。你可能想使用跨瀏覽器的jQuery插件來做到這一點。

順便說一句,這看起來像你想要做一個POST,所以你可能需要增加這個太:

type : 'POST', 

默認情況下,jQuery不會一個GET。

+0

謝謝,那正是我所需要的。我已經嘗試發佈帖子,但收到一條錯誤消息,告訴我「表單編碼的數據不受支持」。使用後+ JSON.stringify它工作正常。 – Zackline 2014-12-04 14:14:02