javascript delay output
I have written some code to display server's current date and time on browser every time user clicks the button . I have done this using ajax in django with the help of jquery. Now my, problem is I have to continously display the date and time once the button is clicked . Some Sample code or utilities allowing such kind of delay will be helpful . Thanks in advance
The template is :
$(document).ready(function()
{
$("button").click(function()
{
$.ajax({
type: "POST",
url :"/showdate/",
datatype: "json ",
success : function(data){
开发者_开发问答 var s = data.currentdate;
var sd = s
$(sd).appendTo("div");
}
});
});
});
<button type="button">Click Me</button>
<div id="someid"></div>
The view function is :
def showdate(request):
now = datetime.datetime.now()
string_now = str(now)
return_dict = {'currentdate':string_now}
json = simplejson.dumps(return_dict)
return HttpResponse(json,mimetype="application/json")
Make JS calculate and display the updated date every second. That way you avoid hitting your server with a new request all the time. Then make a call or example once every ten minutes or so to make sure the client and server is not out of sync.
if you want update thing continuously than use SetIterval
function available in the javascript. which call the function continuously.
check more about setinterval function : http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
sample code :
<form name="myForm" action="" method="POST">
<input name="myClock" type="Text">
<script language=javascript>
self.setInterval('clock()', 50)
function clock() {
time=new Date()
document.myForm.myClock.value=time
}
</script>
</form>
精彩评论