我有这个代码:
var graphicDataUrl = 'templating/graphic-data.json';
var webDataUrl = 'templating/web-data.json';
var templateHtml = 'templating/templating.html';
var viewG = $('#view-graphic');
var viewW = $('#view-web');
$.getJSON(dataUrls, function(data) {
$.get(templateHtml, function(template) {
template = Handlebars.compile(template);
var example = template({ works: data });
viewG.html(example);
viewW.html(example);
});
});
Run Code Online (Sandbox Code Playgroud)
调用两个dataUrl JSON并使用它们的数据以便在我的页面上的两个不同div(#viewW和#viewW)中显示它们的最佳方法是什么?
T.J*_*der 29
最好的方法是单独执行每个操作,并处理错误情况:
$.getJSON(graphicDataUrl)
.then(function(data) {
// ...worked, put it in #view-graphic
})
.fail(function() {
// ...didn't work, handle it
});
$.getJSON(webDataUrl, function(data) {
.then(function(data) {
// ...worked, put it in #view-web
})
.fail(function() {
// ...didn't work, handle it
});
Run Code Online (Sandbox Code Playgroud)
这允许请求并行发生,并在每个请求完成时尽快更新页面.
如果要并行运行请求但等待更新页面直到它们都完成,您可以使用以下命令$.when:
var graphicData, webData;
$.when(
$.getJSON(graphicDataUrl, function(data) {
graphicData = data;
}),
$.getJSON(webDataUrl, function(data) {
webData = data;
})
).then(function() {
if (graphicData) {
// Worked, put graphicData in #view-graphic
}
else {
// Request for graphic data didn't work, handle it
}
if (webData) {
// Worked, put webData in #view-web
}
else {
// Request for web data didn't work, handle it
}
});
Run Code Online (Sandbox Code Playgroud)
...但是,由于您在第一个请求返回时没有更新,但页面可能看起来响应性较低,但仅在两者都这样做时才会更新.
Peb*_*bbl 12
万一它对任何可能遇到这种情况的人都有用 - 并且由于jQuery中的Promise的进步 - TJ Crowder的答案现在可以改进为一个简洁而通用的功能:
/**
* Load multiple JSON files.
*
* Example usage:
*
* jQuery.getMultipleJSON('file1.json', 'file2.json')
* .fail(function(jqxhr, textStatus, error){})
* .done(function(file1, file2){})
* ;
*/
jQuery.getMultipleJSON = function(){
return jQuery.when.apply(jQuery, jQuery.map(arguments, function(jsonfile){
return jQuery.getJSON(jsonfile);
})).then(function(){
var def = jQuery.Deferred();
return def.resolve.apply(def, jQuery.map(arguments, function(response){
return response[0];
}));
});
};
Run Code Online (Sandbox Code Playgroud)
然而,关于不向用户提供任何反馈的观点 - 在等待满载时 - 是一个好的.因此,对于那些喜欢提供响应式反馈的人来说,这是一个支持进度的稍微复杂的版本.
/**
* Load multiple json files, with progress.
*
* Example usage:
*
* jQuery.getMultipleJSON('file1.json', 'file2.json')
* .progress(function(percent, count, total){})
* .fail(function(jqxhr, textStatus, error){})
* .done(function(file1, file2){})
* ;
*/
jQuery.getMultipleJSON = function(){
var
num = 0,
def = jQuery.Deferred(),
map = jQuery.map(arguments, function(jsonfile){
return jQuery.getJSON(jsonfile).then(function(){
def.notify(1/map.length * ++num, num, map.length);
return arguments;
});
})
;
jQuery.when.apply(jQuery, map)
.fail(function(){ def.rejectWith(def, arguments); })
.done(function(){
def.resolveWith(def, jQuery.map(arguments, function(response){
return response[0];
}));
})
;
return def;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29797 次 |
| 最近记录: |