自从我尝试使用JavaScript已有一段时间以来,请耐心等待。我正在开发一个提供学生数据报告的应用程序。后端是PHP。
我们用于这些报告的数据库必须不时从中央仓库中刷新。刷新由最终用户决定,由于各种原因(不值得在此处介绍)而无法自动进行。
刷新至少需要10分钟。因此,浏览器坐在那里加载这么长的时间而没有反馈到用户会很痛苦。我认为向用户提供反馈的最佳方法是通过一个简单的JQuery脚本,该脚本使用户始终了解更新进度。
这是脚本:
var n = 0;
function increment() {
n++;
return n;
}
$(document).ready(function() {
$("#popme").click(function(event) {
n = 0;
$.getJSON('/path/to/json_pids', function(data) {
var numRecords = data.length;
$("#pop-result").html('<p>' + numRecords + ' records</p>');
$.each(data, function(row) {
$.ajax({
url: '/path/to/json_student_info/' + this,
success: function() {
increment();
$("#pop-result").html('<p>' + n + ' / ' + numRecords + ' records</p>');
}
});
});
});
});
});
该脚本中发生了什么:
有一个div
与pop-result
该得到更新ID。在/path/to/json_pids
返回匹配的学生ID的JSON数组。
从那里开始,脚本循环遍历每个记录并调用/path/to/json_student_info/{student_id}
,但不需要任何回报。第二个URL在后端调用脚本,该脚本在报告数据库中创建/更新该学生的记录。
成功后,脚本应该增加显示的数字,pop-result
以便用户可以看到脚本完成的进度。
结果和我的问题
结果有点混乱。JS控制台显示了一整行ERR_INSUFFICIENT_RESOURCES
错误。该脚本永远不会完全遍历所有记录。在约11,000条记录中,它可能达到约4,000条,并因此而死。
我觉得我在这里犯了一个菜鸟错误。在过去的几天里,我一直在寻找类似的情况,但没有找到任何有用的方法。我能找到的最好的主意是将数据分成多个块,但我仍然会收到相同的错误和行为。是否有替代/更好的方法来完成我要完成的任务,或者使该脚本在浏览器上的使用强度降低?
我确定以下代码仍会优化,但这是一种受限制的方法:
$(document).ready(function() {
// Declare variable to hold data...
var results = [],
length = 0;
$("#popme").click(function(event) {
// Get Data
$.getJSON('/path/to/json_pids', function(data) {
// Store returned results in value accessible by all functions
results = data;
length = results.length;
$("#pop-result").html('<p>' + length + ' records</p>');
processItem();
});
});
function processItem() {
// Check length, if 0 quit loop...
if(results.length) {
// Make a call always referencing results[0] since we're shfiting the array results...
$.ajax({
url: '/path/to/json_student_info/' + results[0],
success: function() {
$("#pop-result").html('<p>' + ((length - results.length) + 1) + ' / ' + length + ' records</p>');
// Remove the first item to prepare for next iteration...
results.shift();
// Yay! for recursive functions...
processItem();
}
});
}
}
});
从理论上讲,这应该在上一个项目完成处理后递归调用下一个项目的服务。换句话说,这将使操作看起来像是同步的,因为一次将只处理一次,但是它使用了回调,与async
上面提到的标志相反,该标志已被弃用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句