[英]How to wait until getJSON has gotten all records in jQuery
I have this script where I pull through photos from Flickr using jQuery. 我有这个脚本,可以使用jQuery浏览Flickr中的照片。 I'm using the zFlickrFeed script. 我正在使用zFlickrFeed脚本。 I need to pull through 300 images from Flickr but currently I'm getting 20 pulled through. 我需要从Flickr中提取300张图像,但目前我正在提取20张图像。 I think this is because my getJSON
method is interrupted before it is finished. 我认为这是因为我的getJSON
方法在完成之前被中断了。
How do I wait until all 300 have gone and then call my conditional methods? 我如何等待所有300个都用完之后再调用我的条件方法? The methods in the condition essentially render the JSON data into either a grid or list style layout. 条件中的方法实质上将JSON数据呈现为网格或列表样式布局。
(function($){
$.fn.flickrfeed = function(userid, tags, options) {
// Set plugin defaults
var defaults = {
limit: 300,
header: true,
layout: 'list',
imagesize: 'small',
titletag: 'h4',
title: true,
description: true,
date: true
};
var options = $.extend(defaults, options);
// Functions
return this.each(function(i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('flickrFeed')) $e.addClass('flickrFeed');
// Define Flickr feed API address
var api = 'http://api.flickr.com/services/feeds/photos_public.gne?lang=en-us&format=json&jsoncallback=?';
if (userid != '') api += '&id=' + userid;
if (tags != '') api += '&tags=' + tags;
// Send request
$.getJSON(api, function(data) {
// Process the feeds
if(options.layout == 'list') {
_callback(e, data, options);
}
else if(options.layout == 'grid') {
_altcallback(e, data, options);
}
});
});
};
I would create a counter and once it hits the required number of calls, i'd hit the success function. 我将创建一个计数器,一旦它达到所需的呼叫次数,便会触发成功功能。
i'd add: var counter = this.length
and in the $.getJSON success function, i'd add: if (--counter > 0) return;
我将添加: var counter = this.length
并在$ .getJSON成功函数中添加: if (--counter > 0) return;
this is the code: 这是代码:
var counter = this.length;
return this.each(function(i, e) {`
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('flickrFeed')) $e.addClass('flickrFeed');
// Define Flickr feed API address
var api = 'http://api.flickr.com/services/feeds/photos_public.gne?lang=en-us&format=json&jsoncallback=?';
if (userid != '') api += '&id=' + userid;
if (tags != '') api += '&tags=' + tags;
// Send request
$.getJSON(api, function(data) {
if (--counter > 0) return;
// Process the feeds
if(options.layout == 'list') {
_callback(e, data, options);
}
else if(options.layout == 'grid') {
_altcallback(e, data, options);
}
});
});
Did you try rewriting the getJSON to the full-fledged $.ajax call and then use a .done() or success function call ? 您是否尝试过将getJSON重写为功能完善的$ .ajax调用,然后使用.done()或成功函数调用?
$.ajax({ url: api }).done(function(data) { // Process the feeds });
OR 要么
$.ajax({ url: api success: function(data) { // Process the feeds } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.