2011-06-03 88 views
3

我試圖調用Google API,來自Firefox擴展的JSON發佈請求,例如如何在Firefox擴展中創建JSON發佈請求?

POST https://www.googleapis.com/urlshortener/v1/url 
Content-Type: application/json 

{"longUrl": "http://www.google.com/"} 

如何調用此API並處理Firefox擴展中的響應?

回答

2

最簡單的方法就是使用XMLHttpRequest,就像您在網頁上做的一樣(只是網頁受到同源策略的限制)。

var request = new XMLHttpRequest(); 
request.open("POST", "https://www.googleapis.com/urlshortener/v1/url"); 
request.setRequestHeader("Content-Type", "application/json"); 
request.overrideMimeType("text/plain"); 
request.onload = function() 
{ 
    alert("Response received: " + request.responseText); 
}; 
request.send('{"longUrl": "http://www.google.com/"}'); 

要序列化和解析JSON,請參閱https://developer.mozilla.org/En/Using_native_JSON