如何在firefox扩展中创建JSON post请求?

时间:2011-06-03 18:46:57

标签: ajax json firefox firefox-addon google-api

我正在尝试调用Google API,这是来自Firefox扩展程序的JSON帖子请求,例如

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

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

如何调用此API并在Firefox扩展中处理响应?

1 个答案:

答案 0 :(得分: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