Ich versuche, mit jQuery auf die Instagram-API zuzugreifen
Frage
Ich versuche, die Instagram-API zu verwenden und mache AJAX-Anfragen in einer Do-While-Schleife, bis next_url null ist.Ich möchte lediglich, dass dieser Code alle Follower abruft, indem er fortlaufend Anfragen stellt, bis er fertig ist.Was ist an diesem Code falsch?
Wenn ich die do-while-Schleife entferne, erhalte ich keinen Fehler, aber sobald ich die AJAX-Anfrage innerhalb einer Schleife verwende, stoppt sie nie.Ganz klar das $next_url
Die Zeichenfolge ändert sich nicht in die neu abgerufene Zeichenfolge next_url
- Warum?Was ist falsch?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
Nachdem meine Logik versagt hatte, fügte ich das hinzu $count
Variable, die die do-while-Schleife unterbrechen kann, da die do-while-Schleife unendlich lief.Nach dem Hinzufügen läuft es immer noch unendlich, und ich habe keine Ahnung, warum.
Lösung
Lassen Sie die Funktion sich selbst im Ajax-Erfolgsrückruf mit der neuen URL als Parameter aufrufen:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}