我希望生成的隨機數應打印在網頁上,即通過HttpResponse(x)
每隔5秒後打印一次,對此我已使用time.sleep
函數。Django隨機值打印
如何在不刷新頁面的情況下打印隨機生成的值?
這裏是我的view.py文件
def main(request):
return render(request,'graphs/index.html')
def random_generator(request):
return HttpResponse(randrange(0, 5))
Urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'random/','apps.graph.views.main', name = 'graph_home'),
url(r'random_gen/','apps.graph.views.random_generator', name = 'random'),
)
模板
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function refreshRandom() {
$.ajax({
url: 'random/',
dataType: 'html',
success: function(data) {
$('#random').html(data);
},
complete: function() {
window.setTimeout(refreshRandom, 5000);
}
});
}
window.setTimeout(refreshRandom, 5000);
</script>
</head>
<body>
<div id='random'></div>
</body>
</html>
要哪個視圖設置我的網址?? 'index'視圖還是'random_generator'視圖? – PythonEnthusiast
目前它是'url(r'home /','apps.graph.views.WHICH VIEW'),' – PythonEnthusiast
'url(r'random /','apps.graph.views.random_generator')' –