向阵列添加JSON响应时出错

时间:2013-11-14 21:03:09

标签: javascript arrays json

我正在尝试使用goog.gl api缩短网址。感谢@Barmar现在我可以使用以下代码获取我的短网址:

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;
        }
    });
}

2 个答案:

答案 0 :(得分:2)

这是一个经典的JavaScript问题。在success函数中,每个AJAX调用都使用相同的k。您需要为每次迭代捕获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;
        }
    });
}

答案 1 :(得分: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;
        }
    });
});