我接手了一个网站的维护与开发工作。该网站在某些地方使用了JavaScript/AJAX来显示处理过程中进度条。我编写了自己的脚本用于提取数据库记录,希望在处理过程中也能显示进度条。
目前,我无法理解JavaScript组件的工作方式。当我使用它时,进度条会立即显示为100%,但这发生在任何处理开始之前。我无法弄清楚如何改变这一现象,并在处理过程的不同阶段调用脚本函数。我已经附上了我的PHP脚本和JavaScript脚本,以便您了解我正在处理的内容。
我的提取过程分为两部分。第一部分显示标准网页结构,仅提示用户点击“提取”按钮。点击按钮后,会触发upload_image
脚本,进而“链式”调用实际执行提取目击记录的PHP脚本。
<?php
/* export_sightings.php
导出cbcrecords中所有目击记录到CSV文件
*/
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/standard_page_start.php');
?>
<!-- ================================ -->
<!-- ***** 主要内容开始 ***** -->
<section class="main-container padding-bottom-clear">
<div class="container">
<div class="row">
<div class="main col-12">
<h3 class="title">将目击记录导出为CSV</h3>
<div class="separator-2"></div>
<p>使用此工具将目击数据导出为CSV文件,并通过电子邮件发送给您。</p>
</div>
</div>
<div class="row">
<div class="main col-12">
<form action="src/export_sightings.php"
id="myForm"
name="frmupload"
method="post"
enctype="multipart/form-data">
<input type="submit"
name='startextract'
class="submit-button btn btn-sm btn-default"
value="开始提取"
onclick='upload_image();'/>
</form>
<div class="progress" id="progress_bar">
<div class="bar" id="bar"><p class="text-white text-center">正在提取数据...</p><br></div>
<div class="percent" id="percent">0%</div>
</div>
<p class="text-danger mt-4"><i class="fa fa-warning"></i> 点击“开始提取”后,请等待下方出现黄色确认框。根据需要提取的记录数量,这可能需要一段时间!</p>
<div class="output_image" id="output_image"></div>
</div>
</div>
</div>
</section>
<!-- ***** 主要内容结束 ***** -->
<!-- ================================ -->
<?php include 'inc/standard_page_end.php'; ?>
以下是JavaScript脚本progress.js
:
function upload_image()
{
console.log('调用了progress.js脚本');
var bar = $('#bar');
var percent = $('#percent');
$('#myForm').ajaxForm({
beforeSubmit: function() {
document.getElementById("progress_bar").style.display="block";
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
console.log(percentVal);
},
complete: function(xhr) {
if(xhr.responseText)
{
document.getElementById("output_image").innerHTML=xhr.responseText;
}
}
});
}
在我看来(基于我有限的经验),似乎应该能够单独调用uploadProgress
和success
函数,但我无法弄清楚如何实现。目前看来,这两个函数似乎是自我执行的。
我详细查看了网站中其他使用进度条的两个部分,但除了在核心脚本progress.js
中找到调用外,未能找到其他调用方式。