如何使用jQuery ajax请求web service并显示进度信息

net205 net205 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我在开发中,有一个恢复网站的操作,比较耗时,我想在操作时往缓存中记录当前操作进度,然后另一个请求获取当前操作的进度即时显示在客户端显示。

问题:是另一个请求不能即时显示进度,而只是最后一次请求才可以改变进度条。

类似代码 WebService.ashx(c#):
public class WebService : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string invoke = string.Empty;
string jsoncallback = string.Empty;

if (!string.IsNullOrEmpty(context.Request["invoke"]))
invoke = context.Request["invoke"].ToString().Trim();
if (!string.IsNullOrEmpty(context.Request["jsoncallback"]))
jsoncallback = context.Request["jsoncallback"].ToString().Trim();

context.Response.ContentType = "application/x-javascript; charset=utf-8";
switch (invoke.ToLower())
{
case "call":
int currentValue = 0;
int TotalValue = 100;
HttpContext.Current.Cache.Remove("progress");
HttpContext.Current.Cache.Insert("progress", currentValue + "," + TotalValue, null,
DateTime.Now.AddMinutes(60),System.Web.Caching.Cache.NoSlidingExpiration);

for (int i = 1; i <= TotalValue; i++)
{
currentValue = i;
//TODO...
HttpContext.Current.Cache.Insert("progress", currentValue + "," + TotalValue, null,
DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration);
Thread.Sleep(100);
}
context.Response.Write(string.Format("{0}({{error:{1}, message:\"{2}\"}})", jsoncallback, false.ToString().ToLower(), "finished."));
break;
case "progress":
string progress = "100,100";
if(HttpContext.Current.Cache["progress"] != null)
{
progress = HttpContext.Current.Cache["progress"].ToString();
}
context.Response.Write(string.Format("{0}({{error:{1}, message:\"{2}\"}})", jsoncallback, false.ToString().ToLower(), progress));
break;
default:
context.Response.Write(string.Format("{0}({{error:{1}, message:\"{2}\"}})", jsoncallback, false.ToString().ToLower(), "parameter error."));
break;
}
}

public bool IsReusable
{
get{return false;}
}
}


页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style>
.ProgressBar {
position:relative;
margin-top:30px;
margin-bottom:20px;
margin-left:240px;
width: 220px;
border: 1px solid #B1B1B1;
overflow: hidden;
}
.ProgressBar div {
position:relative;
background: #2BD029;
color: #333333;
height: 15px;
line-height: 15px;
text-align:left;
}
.ProgressBar div span {
position:absolute;
width: 220px;
text-align: center;
font-weight: bold;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var intervalID;

function RequestProcess(){
$.getJSON("http://localhost:4397/webservice.ashx?invoke=progress&jsoncallback=?", function(data) {
var progress = data.message;
var position = parseInt(progress.split(",")[0] / progress.split(",")[1] * 100);
if(isNaN(position))
position = 0;
$('#divMessage').append("<br/>"+position);
if (position >= 100) stopRequestProcess();
$('.ProgressBar > div').css({ "width": position + "%" });
$('.ProgressBar > div > span').html(position + "%");
$('#ProgressInfo').html(position >= 100 ? "finished" : position);
});
}
function stopRequestProcess(){
clearInterval(intervalID);
}

$(document).ready(function(){
$('#btnStart').click(function(){
$('#divMessage').html('');
$.ajax({
type: "GET",
url: "http://localhost:4397/webservice.ashx?invoke=call&jsoncallback=?",
dataType: "jsonp",
async: false,
error: function(xhr, ajaxOptions, thrownError) {
stopRequestProcess();
},
success: function(response) {
stopRequestProcess();
$('.ProgressBar > div').css({ "width": "100%" });
$('.ProgressBar > div > span').html("100%");
$('#ProgressInfo').html("finished");
}
});

intervalID = setInterval(RequestProcess, 500);
});
});
</script>
</head>

<body>
<div>
<div>
<div class="ProgressBar" style="*margin-left:0px" align="left">
<div style="width:0%;*margin-left:0px"><span>0%</span></div>
</div>
<div id="ProgressInfo" class="ProgressInfo">processing...</div>
</div>
<button id="btnStart" name="btnStart">start</button>
</div>
<br/>Progress Information:<br/>
<div id="divMessage"></div>
</body>
</html>

...全文
评论 13
收藏 已收藏
分享
返回顶部
net205
JavaScript 87,984 成员 224,681 内容