如何在Firefox扩展中创建一个JSON POST请求?

3

我正在尝试从Firefox扩展中调用Google API,需要进行JSON post请求,例如:

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

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

我该如何在Firefox扩展中调用此API并处理响应?
1个回答

3

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接