姜戈,JavaScript &Co. : 在 html 上打印 python 文件上的变量 运行

Django, JavaScript &Co. : Print on html a variable running on python file

我写了这个简单的例子:我有一个函数 x = 100*Math.random(),每隔 t = 1000 ms 打印一个数字。好的,有效。

我的问题是:如何 use/call 外部 python 函数(例如 x = counter.py)而不是 x = 100*Math.random()

somepage.html

    ... 
    <script  src="{% static 'jquery-1.11.2.js' %}"></script>
    <script src="{% static 'js/contaBIS.js' %}"></script>
    <button type="button" class="btn btn-success" id="start"> START </button>
    <p id ="A"></p>
    <p id ="B"></p>
    ...

contaBIS.js

$(document).ready(function() {
var x;                                      
var t = 1000;


    $('#start').click(function() {

        $('#start')
            .removeClass('btn-success')
            .addClass('btn-warning disabled')
            .text('WAIT'); 

        var myVar=setInterval(function(){myTimer()},t);
        function myTimer() {

        document.getElementById("A").innerHTML="something's working ";

        x = 100*Math.random();         //just an example

        document.getElementById("B").innerHTML= x ;
        }

});

counter.py

import time
z = 0
def prova(z):


    while z < 10:
        time.sleep(1)
        z = z + 1
        print(z)      // I see z only on Eclipse console
    return z

好的, 我看到了如何调用外部函数,但我不知道如何在 html 上查看它的值。我是否必须编写另一个视图才能做到这一点?怎么样?!

我在看print the value of a variable in Python/Django?,但对我来说不是很好。

浏览器无法在网络服务器上执行任何随机代码(其中 Django 运行s),它只能下载页面。

我的第一个赌注是创建一个 Django 视图,它实际上 运行s counter.py 并将其输出呈现为浏览器可以处理的内容。

在您的查看器页面上,您应该包含一个 AJAX 调用以获取上述视图的结果。

但是请注意,您的 counter.py 不存储任何状态信息,这意味着每次您 运行 它时,您都会得到相同的输出:

0
1
2
3
4
5
6
7
8
9

所有这些都在 10 秒内呈现,这对于 AJAX 调用(实际上,对于任何页面加载)的响应时间确实很短。

好的 改变了几件事。我 post 另一个更具体的问题,因为我无法删除这个问题。 在这里引用一下,希望对我这种刚开始学习django的人有用:

Clicking on a html button, I call views.stream_response which "activates" views.stream_response_generator which "activates" stream.py and return a StreamingHttpResponse and I see a progressive list every second up to n at /stream_response/:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

stream.py

import time             
def streamx(n):
    list = []  
    x=0
    while len(list) < n:      
        x = x + 1
        time.sleep(1)
        list.append(x)
        yield "<div>%s</div>\n" % list
    return list

views.py

def stream_response(request):
    n = 10         #I would like to take this value from a FORM on html
    resp = StreamingHttpResponse( stream_response_generator(n))
    return resp    


def stream_response_generator(n):
    res = stream.streamx(n)
    return res

urls.py

...
url(r'^homepage/provadata/$', views.provadata),    
url(r'^stream_response/$', views.stream_response, name='stream_response'),
...

homepage/provadata.html

<a href="{% url 'stream_response' %}" class="btn btn-info" role="button" id="btnGo">GO</a>