2013-11-14 4 views
0

goog.gl api를 사용하여 URL 단축키를 만들려고합니다. @Barmar 덕분에이 코드를 사용하여 짧은 URL을 얻을 수 있습니다 :배열에 JSON 응답을 추가하는 중 오류가 발생했습니다.

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

하지만 링크 배열을 단축하고 싶습니다! 그래서 루프를 사용하기로 결정했습니다. [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

문제는 당 기능 폐쇄 변수가 아니기 때문에 모든 콜백 함수는, 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; 
     } 
    }); 
}); 
+0

두 번째 변형은 잘 작동하고 나를 더 아름답고 논리적으로 보입니다. –

2

이 고전 자바 스크립트 문제를

나는이 코드를 실행하면 longURL [] 및 SHORTURL은 []하지만 난 SHORTURL 배열에 같은 출력을 얻을 만들었습니다. 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; 
     } 
    }); 
} 
관련 문제