Use Ajax to update progress of process running in codebehind
This is a followup on a question I asked earlier.
Update a We开发者_如何学运维b Page as a Process Runs
I want the webpage to display what stage the process is running using Ajax. After each step in the code behind, a file is overwritten with some text indicating what just happened. I want the webpage to periodically send a request for that file and display its contents using either setInterval or setTimeout. Once the button is pressed, the webpage starts its request cycle and the server begins its time consuming operation.
What I have now...
Script for periodic requests:
<script type="text/javascript">
var d = setInterval("Check()", 3000);
function Check() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
alert("get chrome");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.getElementById("s").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "temp/test.txt", true);
xmlhttp.send();
}
/*$(document).ready(function () {
$("#uploadbutton").click(Check());
});*/
</script>
Currently Check() starts running as soon as the page loads. I would like it to only be called once the click event happens. If I define the Check() inside the click event, it doesn't recognize the setInterval and will only check if I click the button again. This isn't a huge problem as I think it will be ok to have the script running. It will just display a "not searching" string. Unfortunately as the file gets updated (and I checked that it was) the page does not display the contents as it gets the response. It just remains the same, then once the codebehind finishes, it resets to the default setting. Can anyone tell me why the page isn't updating?
edit: forgot to mention that the click event has an onclick assigned to the C# codebehind that does the long function. I don't know if I can have the javascript Ajax function running and the C# codebehind going too. The Ajax calls have async = true, but the script part isn't running parallel to codebehind right?
edit again: I changed the script to count upwards. I expected it to continue to count while the codebehind did its thing, but once you hit the button it stops. Once the codebehind finishes it restarts the count. Why doesn't the counting keep going? I expect it to restart once the codebehind is finished, but I thought it would keep counting.
setInterval("Check()", 3000);
should be called on the button click event. Don't invoke Click()
directly on the button click event, just invoke the setInterval("Check()", 3000);
and it will invoke Click()
for you.
精彩评论