我继承了一个网站的维护/开发。在一些地方,它使用 Javascript/AJAX 在处理过程中显示进度条。我已经编写了自己的脚本来提取数据库记录,并且我想在执行此操作时显示进度条。
我无法理解 Javascript 组件是如何工作的。当我使用它时,进度条立即显示 100%,但这是在进行任何处理之前。我不知道如何更改此设置并在处理的各个阶段调用脚本函数。我已附上我的 PHP 脚本和 Javascript 脚本,以便您可以看到我正在使用的内容。
我的提取过程分为两部分。第一部分显示我的标准网页结构,并简单地要求用户点击“提取”按钮。当用户单击按钮时,这会调用 upload_image 脚本,然后“链接”到实际提取目击记录的 PHP 脚本。
<?php
/* export_sightings.php
Export all sightings records from cbcrecords as CSV file
*/
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/standard_page_start.php');
?>
<!-- ================================ -->
<!-- ***** MAIN CONTENT START ***** -->
<section class="main-container padding-bottom-clear">
<div class="container">
<div class="row">
<div class="main col-12">
<h3 class="title">Export sightings to CSV</h3>
<div class="separator-2"></div>
<p>Use this tool to extract sightings data to a CSV which will be sent to you by email.</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="START EXTRACT"
onclick='upload_image();'/>
</form>
<div class="progress" id="progress_bar">
<div class="bar" id="bar"><p class="text-white text-center">extracting the data...<br><br></p></div>
<div class="percent" id="percent">0%</div>
</div>
<p class="text-danger mt-4"><i class="fa fa-warning"></i> Please wait for the yellow confirmation box to appear below once you have clicked 'START EXTRACT'. Depending upon the number of records to be extracted, this may take a while!</p>
<div class="output_image" id="output_image"></div>
</div>
</div>
</div>
</section>
<!-- ***** MAIN CONTENT END ***** -->
<!-- ================================ -->
<?php include 'inc/standard_page_end.php'; ?>
这是Javascript脚本progress.js
function upload_image()
{
console.log('Hit the progress.js scritpt');
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之外,我找不到任何对该函数的调用
这些是分配给(jquery 插件?)“ajaxForm”的 javascript 对象文字中的属性的匿名函数(lambda),您无法从这里自己以任何方式访问它们,这是为了 ajaxForm 函数的工作。
似乎您使用了一个名为 ajaxForm 的插件(https://jquery-form.github.io/form/)
你说得对,uploadProgress是处理进度的关键函数。你需要查找他们的文档来了解如何在 PHP 中实现它。