当内容长度等于0时,jquery ajax进度条

时间:2017-02-10 21:03:09

标签: javascript php jquery ajax jqxhr

我尝试将jQuery AJAX用于我的目标,但我遇到了问题。



$('#go').on('click',function(evt){
    evt.preventDefault();
    $(this).hide();
    $('#progress-bar').show();

    console.log('starting ajax request');
    $.ajax({
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener('progress', function (e) {
                console.log(e);
                if (e.lengthComputable) {
                    $('.progress-bar').css('width', '' + (100 * e.loaded / e.total) + '%');
                }
            });
            return xhr;
        },

        type: 'POST',
        url: 'core.php',
        data: {},
        complete: function (response, status, xhr) {
            console.log(response);
            $('.desc').html(response.responseText);
        }
    });

});

.container-fluid {
	padding-top: 20px;
}
#progress-bar {
	margin-top: 20px;
	display: none;
	width: 100%;
}

<html>
<head>
	<link rel="stylesheet" href="style.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
  <body>
	<div class="container-fluid">
		<a class="btn btn-default" id="go">Let's go!</a>
		<div class="progress" id="progress-bar">
			<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">

			</div>
		</div>
		<div class="desc">

		</div>
	</div>
	<script src="ajax.js"></script>
</body>
</html>
&#13;
&#13;
&#13;

core.php 中,我应该对数组执行一些功能。例如,它将是:

<?php
$sum = 0;
for ($i=0; $i<9999; $i++) {
    $sum++;
}
?>

我的javascript结构不起作用。我知道这是因为 xhr 中的 e.lengthComputable 。我还发现 core.php 标题包含 Content-Length:0 。好。但是我应该怎么做才能正确地执行我的ajax请求并拥有动态进度条?

谢谢!

0 个答案:

没有答案