如何在Firefox扩展中创建JSON发布请求?

问题描述:

我试图调用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扩展中的响应?

最简单的方法就是使用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