我正在尝试使用 goog.gl api 制作网址缩短器。感谢@Barmar,现在我可以使用以下代码获取我的短 URL:
var shortURL;
$.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) {
shortURL = response.id;
}
});
但我想缩短一系列链接!所以我决定使用循环。
我创建了 longURL[] 和 shortURL[] 但如果我运行这段代码,我会在 shortURL 数组中得到这样的输出:[undefined × 10, "http://goo.gl/AxzWLx"];
完整代码:
var longURL = [];//there are some urls
var shortURL = [];
for (var k = 0; k < longURL.length; k++) {
$.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[k] +'"}',
dataType: 'json',
success: function(response) {
shortURL[k] = response.id;
}
});
}