我正在编写我的第一个 google chrome 扩展,它将使用 Google's URL shortener api缩短 Chrome 中当前事件标签的 URL。
我是一名长期的 sw 开发人员 (asm/C++),但对这种“webby”的东西完全陌生。 :)
我似乎无法弄清楚如何使用 js 或 jquery 发出(然后处理)http POST 请求。我想我只是不了解 curl 示例之外的 POST 机制。
我的 javascript 文件目前看起来像这样:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
});
最佳答案
最简单的解决方案是使用 jquery 的 $.ajax
函数。这将允许您将内容异步发送到 google。当数据返回时,您可以继续处理响应。
代码看起来像this question
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response); // Evaluate the J-Son response object.
}
});
关于javascript - 在 Google Chrome 扩展程序中使用 javascript 访问 Google 的 URL shortener API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12696704/