【问题标题】:Django Ajax simple Get functionDjango Ajax 简单获取函数
【发布时间】:2014-02-16 13:14:04
【问题描述】:

首先,很抱歉这个愚蠢的问题,但我不是程序员,所以请原谅我:)

我用 Python 编写了简单的代码来读取通过串口发送的数据。 它的工作真的很棒。

编辑:

在 vadimchin 的帮助下,我设法做到了这样的事情。

views.py

class ViewVolt(TemplateView):
template_name = 'view_volt.html'

def __init__(self, voltage=''):
    self.voltage = voltage
    rs232 = serial.Serial(
                     port = 'COM15',
                     baudrate = 38400,
                     parity = serial.PARITY_NONE,
                     stopbits = serial.STOPBITS_ONE,
                     bytesize = serial.EIGHTBITS,
                     timeout = 1) 
    line = rs232.readline().decode('utf-8')
    if ( 'Pomiar 1' in line ):
        index_current = line.find('Prąd')
        index_voltage = line.find('Napięcie')
        current = line[index_current+6:index_current+11]
        self.voltage = line[index_voltage+9:index_voltage+14] 

def get_context_data(self, **kwargs):

    context = super(ViewVolt, self).get_context_data(**kwargs)
    context['ajax_var'] = self.voltage
    context['is_ajax'] = self.request.is_ajax()
    return context

我现在要做的是在我的网页上只显示电压值。

urls.py

url(r'^volt/$', ViewVolt.as_view(), name='view_volt'),

view_volt.html

    {% if is_ajax %}
    <h1>from ajax: {{ ajax_var }}</h1>
{% else %}
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
       <script language="javascript" type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.min.js"></script>
        <script type="text/javascript">

            $(function () {
                var ping_tm = null;

                function _ping() {
                    $.get('', function (result) {
                        clearTimeout(ping_tm);
                        $("div").empty();
                        $("div").append(result);

                        ping_tm = setTimeout(_ping, 1000);
                    })
                }

                _ping();

            });

        </script>
    </head>
    <body>
    <div></div>
    my doc
    </body>
    </html>
{% endif %}

如您所见,我对您的 view_volt.html 模板和您的 View_volt 类进行了一些修改,但仍然无法正常工作。

这是一个屏幕截图。

![结果1]

我不知道为什么它一直没有从我的串口获取值。

提前谢谢...

【问题讨论】:

    标签: ajax json django get


    【解决方案1】:

    views.py

    logger = logging.getLogger('volt')
    
    class ViewVolt(TemplateView):
        template_name = 'frontend/view_volt.html'
    
        def get_context_data(self, **kwargs):
            context = super(ViewVolt, self).get_context_data(**kwargs)
    
            logger.debug('my info')
    
            context['ajax_var'] = '1234'
            context['is_ajax'] = self.request.is_ajax()
            return context
    

    view_volt.html

    {% if is_ajax %}
        <h1>from ajax: {{ ajax_var }}</h1>
    {% else %}
        <!doctype html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Document</title>
            <script type="text/javascript" src="/static/js/jquery-2.1.0.min.js"></script>
            <script type="text/javascript">
    
                $(function () {
                    var ping_tm = null;
    
                    function _ping() {
                        $.get('', function (result) {
                            clearTimeout(ping_tm);
    
                            console.log(result);
    
                            ping_tm = setTimeout(_ping, 1000);
                        })
                    }
    
                    _ping();
    
                });
    
            </script>
        </head>
        <body>
        my doc
        </body>
        </html>
    {% endif %}
    

    urls.py

    urlpatterns = patterns('',
       url(r'^volt/$', ViewVolt.as_view(), name='view_volt'),
    )
    

    或者你可以使用 websocket + gevent

    在settings.py中添加

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse'
            }
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            },
            'file': {
               'class': 'logging.handlers.RotatingFileHandler',
               'level': 'DEBUG',
               'filename': 'log.log'
            }
        },
        'loggers': {
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
            'volt': {
               'handlers': ['file'],
               'level': 'DEBUG'
            }
    
        }
    
    }
    

    【讨论】:

    • 这个变量 {{ ajax_var }} 如何在localhost:8000/volt 下显示而不是在 标签内?
    • 替换 console.log(result) 例如 - $('body').append(result)
    • vadimchin:我稍微修改了您的代码,离实现我的目标又近了一步,但我遇到了上述另一个问题。
    • 尝试使用日志记录(见修改后的代码),也许你需要将所有数据从构造函数移动到 get_context_data
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多