0

goog.gl api を使用して短縮 URL を作成しようとしています。@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 に答える