简体   繁体   English

Javascript进度仅在第二个表单提交后有效

[英]Javascript progress only works after second form submit

I have a script for file and image uploads, and when you submit the file, there's javascript that shows a percentage of how much it's done, but this only works on the second time you submit it. 我有一个用于上传文件和图像的脚本,当您提交文件时,有一个javascript显示了完成的百分比,但这仅在您第二次提交时起作用。 Ex. 例如 If you upload one picture, then upload one right after it only works the second time. 如果您上传一张图片,则仅在第二次上载后立即上传一张。 This is the JS: 这是JS:

<script>
    $(function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        }
    });
    }); 
</script>

And the Form: 和形式:

<div class="bar"></div>
<div class="percent">0%</div>
<div id="status"></div>
<form enctype="multipart/form-data" method="post" action="/uploadphoto">
<fieldset>
<legend>Picture Upload</legend>
<label for="name">Picture Name:</label><br />
<input type="text" id="name" name="name" value="" /><br />';
echo'<select id="cat" name="cat">';
$query = "SELECT * FROM gallery_cat";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data)) {
    echo '<option value="'.$row['cg_id'].'">'.$row['cg_name'].'</option>';
}
echo'</select><br /><br />';    
echo'
<label for="desc">Description</label><br />
<textarea id="desc" name="desc" rows="4" cols="30"></textarea><br />
<label for="file">Picture:</label>';
echo'<input type="file" id="file" name="file" />
</fieldset>
<input type="submit" value="Save Picture" name="submit" /> <a class="button" href="/viewgallery">Cancel</a>

Please keep in mind that I'm new to JS. 请记住,我是JS新手。 The PHP in the form is to select which gallery to upload to, and it shouldn't affect the JS. 表单中的PHP是选择要上载到哪个库,并且不应该影响JS。

 Initialize the form when dom is ready.Try this one,
 $(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('form').ajaxForm(function() { 
            beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal);
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal);
        percent.html(percentVal);
    } 
        }); 
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM