0

我正在尝试使用 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;
        }
    });
}
4

2 回答 2

2

这是一个经典的 JavaScript 问题。在您的success函数中,您k对每个 AJAX 调用都使用相同的方法。您需要捕获k每次迭代的值。

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',
        context: {key: k}, // the "this" value in the callback
        success: function(response) {
            shortURL[this.key] = response.id;
        }
    });
}
于 2013-11-14T21:06:47.110 回答
2

问题是你所有的回调函数共享相同的值k,因为它不是每个函数的闭包变量。您可以使用该context:选项将适当的值传递给每个回调。

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',
        context: k,
        success: function(response) {
            shortURL[this] = response.id;
        }
    });
}

另一种解决方案是使用$.each(). 由于每次迭代都是一个函数调用,因此您将关闭参数:

var longURL = [];//there are some urls
var shortURL = [];
$.each(longURL, function(k, url) {
    $.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: "' + url +'"}',
        dataType: 'json',
        success: function(response) {
            shortURL[k] = response.id;
        }
    });
});
于 2013-11-14T21:07:36.167 回答