JavaScript函数未运行

时间:2016-08-10 06:05:34

标签: javascript html ajax django

我已经定义了两个JavaScript函数来进行ajax请求,问题是如果我在setInterval()函数中调用我的函数,它可以工作,但是如果我调用我的函数而没有setInterval不能正常工作,这是我的代码:

如果我使用setInterval函数,我使用的服务器无法以1s频率处理所有获取请求,那么我想在您为网页收费时调用ajax,然后每20秒对于exameple。谢谢!

功能定义和调用不起作用:

function sync_vitrasa(id){
    $.ajax({
        url: "/vitrasa_state/",
        type:"GET",
        data: {
            id: id,
        },
        success: function( data ) {
            id="#zv"+id;
            $(id).html(data);
        }
    });
}

function sync_pet(id){
    $.ajax({
        url: "/traffic_ligths_state/",
        type:"GET",
        data: {
            id: id,
        },
        success: function( data ) {
            id="#zs"+id;
            $(id).html(data);
        }
    });
}


sync_vitrasa(1);
sync_pet(1);

有效的函数调用:

setInterval("sync_vitrasa(8)",1000);
setInterval("sync_pet(1)",1000);

以下是完整的HTML代码:

{% extends "base.html" %}
{% block styles %}
<link rel="stylesheet" type="text/css" media="screen" href="/static/css/bootstrap-datetimepicker.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/static/css/style.css">
    <style type="text/css">
        body {
            padding-top: 10px;
            padding-bottom: 40px;
        }
        /* Custom container */
        .container-narrow {
            margin: 0 auto;
            max-width: 1000px;
        }
        .container-narrow > hr {
            margin: 30px 0;
        }
        .marketing {
            margin: 10px 0;
        }
        .marketing p + h4 {
            margin-top: 28px;
        }
        .errorlist { 
             color:red;
        }
        #map {
            width: 100%;
            height: 500px;
        }
        @media only screen and (max-width: 1000px) {
            /* Force table to not be like tables anymore */
            #no-more-tables table, 
            #no-more-tables thead, 
            #no-more-tables tbody, 
            #no-more-tables th, 
            #no-more-tables td, 
            #no-more-tables tr { 
                display: block; 
            }

            /* Hide table headers (but not display: none;, for accessibility) */
            #no-more-tables thead tr { 
                position: absolute;
                top: -9999px;
                left: -9999px;
            }

            #no-more-tables tr { border: 1px solid #ccc; }

            #no-more-tables td { 
                /* Behave  like a "row" */
                border: none;
                border-bottom: 1px solid #eee; 
                position: relative;
                padding-left: 50%; 
                white-space: normal;
                text-align:left;
            }

            #no-more-tables td:before { 
                /* Now like a table header */
                position: absolute;
                /* Top/left values mimic padding */
                top: 6px;
                left: 6px;
                width: 45%; 
                padding-right: 10px; 
                white-space: nowrap;
                text-align:left;
                font-weight: bold;
            }

            /*
            Label the data
            */
            #no-more-tables td:before { content: attr(data-title); }

    </style>
    {% endblock %}
    {% block body %}
    <div  class="container-narrow">
        <div class="masthead">
            <ul class="nav nav-pills pull-right" style="margin-top: 50px;">
                <li><a href="/logout/">Cerrar sesi&oacute;n</a></li>

            </ul>
            <h3 class="muted">
                <img src="/static/img/****4D-logo.png" width="300px" height="143px"/>
            </h3>
        </div>

        <hr>
        {% load widget_tweaks %}
        <div class="row-fluid marketing">
            <div class="span6">
                <form action="" method="post" >{% csrf_token %}
                    <fieldset> 
                        <legend>Añadir Evento </legend>
                        <div class="control-group">
                            <label class="control-label">Tipo de evento:</label>
                            <div class="controls">
                                {{ form.event_type }}
                                {{ form.event_type.errors }}
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">Posici&oacute;n del evento:</label>
                            <div class="controls form-inline">
                                {% render_field form.lat_position placeholder="Latitude" %}
                                {% render_field form.lon_position placeholder="Longitude" %}
                                {{ form.lat_position.errors }}
                                {{ form.lon_position.errors }}
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">Sentido:</label>
                            <div class="controls">
                                {{ form.direction }}
                                {{ form.direction.errors }}
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">Tiempo de expiraci&oacute;n:</label>
                            <div class="controls">
                                <div id="datetimepicker" class="input-append date">
                                   {% render_field form.expiry_time data-format="dd/MM/yyyy hh:mm:ss" placeholder="dd/MM/yyyy hh:mm:ss" %}  
                                    <span class="add-on">
                                        <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
                                    </span>
                                </div>
                                {{ form.expiry_time.errors }}
                            </div>
                        </div>
                        <button class="btn btn-large btn-primary" name="add_road_event" type="submit">Añadir evento</button>
                    </fieldset>
                </form>
            </div>

            <div class="span6">
                <div class="controls form-inline">
                    <label class="checkbox">
                        <input id="addMarkerSelected" type="checkbox" checked="checked"> Seleccionar posici&oacute;n                
                    </label>
                    <label class="checkbox" style="float:right; margin-top:6px;">
                        <input id="visibilityEvents" type="checkbox"> Visualizar todos los eventos
                    </label>
                </div>
                <div id="map"></div>
            </div>
        </div>

        <div class="row-fluid marketing" style="margin-top:25px;">
            <form action="" method="post">{% csrf_token %}
                <fieldset> 
                    <legend>Lista de eventos activos</legend>
                    {% if road_events|length %}
                    <section id="no-more-tables">
                        <table class="table-bordered table-striped table-condensed cf">
                            <thead class="cf">
                               <tr>
                                  <th>#</th>
                                  <th>Fecha creación</th>
                                  <th>Evento</th>
                                  <th>Latitud</th>
                                  <th>Longitud</th>
                                  <th>Sentido</th>
                                  <th>Tiempo expiración</th>
                               </tr>
                           </thead>
                           <tbody>
                     {% for event in road_events %}
                             <tr>
                                 <td data-title="#">
                                    <label class="checkbox">
                                    <input id="{{event.id}}" name="{{event.id}}" type="checkbox" >
                                    </label>
                                 </td>
                                 <td data-title="Fecha creación">{{ event.created }}</td>
                                 <td data-title="Evento">{{ event.get_event_type_display }}</td>
                                 <td data-title="Change">{{ event.lat_position }}</td>
                                 <td data-title="Latitud">{{ event.lon_position }}</td>
                                 <td data-title="Sentido">{{ event.get_direction_display }}</td>
                                 <td data-title="Tiempo expiración">{{ event.expiry_time }}</td>
                             </tr>
                               {% endfor %}
                          </tbody>
                      </table>
                    </section>
                        <button class="btn btn-large btn-danger" style="margin-top:25px;" name="remove_road_event" type="submit">Eliminar eventos</button>
                    {% else %}
                    Actualmente no hay ningun evento activo.
                    {% endif %}
                </fieldset>
            </form>
        </div>

        <div class="span10" >
        <table width="100%" border="1" bgcolor="#EFFBF8">
            <tr>
                <td colspan="3" rowspan="2" align="center"><b>Zona corredor</b>
                <th colspan="3" align="center" >Prioridad a bus</th>
            </tr>
            <tr>
                <td align="center"><b>Solicitada</b></td>
                <td align="center"><b>Prioridad<br> habilitada
                </b></td>
                <td align="center"><b>Activada</b></td>
            </tr>
            <tr>
                <td colspan="3" bgcolor="#FAAC58">Zona 1 (Avda. Madrid ascendente)</td>
                <td align="center">                     
                    <div id="zv1"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="1" type="checkbox" /> 
                                {% for i in zone %} 
                        {% if i.id == 1 %}
                                {% if i.****_pet == True %} 
                         <img width="40px" src="/static/img/check.png"> <br />
                         <input type="submit" value="Deshabilitar"/> 
                                {%else%} <br/>
                        <input type="submit" value="Habilitar" /> 
                                {%endif%}
                                {%endif%}                           
                            {% endfor %}
                    </form>
                </td>
                <td align="center">
                        <div id="zs1"></div>                            
                </td>                   
            </tr>               
            <tr>
                <td colspan="3" bgcolor="#66CC66">Zona 2 (Avda. Madrid
                    descendente)</td>
                <td align="center">                 
                <div id="zv2"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="2" type="checkbox" /> 
                             {% for i in zone %} 
                                {% if i.id == 2 %}
                                {% if i.****_pet == True %} 
                                    <img width="40px" src="/static/img/check.png"> <br />
                                    <input type="submit" value="Deshabilitar"/> 
                                {%else%} <br/>
                                    <input type="submit" value="Habilitar" /> 
                                {%endif%}
                                {%endif%}                           
                                {% endfor %}
                    </form>
                </td>
                <td align="center">
                        <div id="zs2"></div>
                </td> 
            </tr>               
            <tr>
                <td colspan="3" bgcolor="#FFFF00">Zona 3 (Gran V&iacute;­a  descendente)</td>
                <td align="center">
                    <div id="zv3"></div>    
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="3" type="checkbox" /> 
                                {% for i in zone %} 
                                    {% if i.id == 3 %}
                                    {% if i.****_pet == True %} 
                                        <img width="40px" src="/static/img/check.png"> <br />
                                        <input type="submit" value="Deshabilitar"/> 
                                    {%else%} <br/>
                                        <input type="submit" value="Habilitar" /> 
                                    {%endif%}
                                    {%endif%}                           
                                {% endfor %}
                    </form>
                </td>
                <td align="center">
                    <div id="zs3"></div>                        
                </td>                   
            </tr>           
            <tr>
                <td colspan="3" bgcolor="#58ACFA">Zona 4 (Gran V&iacute;a ascendente)</td>
                <td align="center">
                    <div id="zv4"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                    <input hidden checked name="zone_id" value="4" type="checkbox" /> 
                            {% for i in zone %} 
                            {% if i.id == 4 %}
                            {% if i.****_pet == True %} 
                    <img width="40px" src="/static/img/check.png"> <br />
                    <input type="submit" value="Deshabilitar"/> 
                            {%else%} <br/>
                    <input type="submit" value="Habilitar" /> 
                                {%endif%}
                                {%endif%}                           
                                {% endfor %}
                    </form>
                </td>
                <td align="center">
                    <div id="zs4"></div>                        
                </td> 
            </tr>
            <tr>
                <td colspan="3" bgcolor="#ff4d4d" style="word-wrap:break-word;">Zona 5 (B.Aires-Autopista hasta Rot. Jenaro de la Fuente-Túnel Martínez Garrido)</td>
                <td align="center">
                    <div id="zv5"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="5" type="checkbox" />
                                {% for i in zone %}
                                {% if i.id == 5 %}
                                {% if i.****_pet == True %}
                         <img width="40px" src="/static/img/check.png"> <br />
                         <input type="submit" value="Deshabilitar"/>
                                {%else%} <br/>
                        <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                    {%endfor%}
                    </form>
                </td>
                <td align="center">
                        <div id="zs5"></div>
                </td>
            </tr>
            <tr>
                <td colspan="3" bgcolor="#ff6666">Zona 6 (Rot. Jenaro de la Fuente-Túnel Martínez Garrido hasta B.Aires-Autopista)</td>
                <td align="center">
                    <div id="zv6"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="6" type="checkbox" />
                                {% for i in zone %}
                                {% if i.id == 6 %}
                                {% if i.****_pet == True %}
                         <img width="40px" src="/static/img/check.png"> <br />
                         <input type="submit" value="Deshabilitar"/>
                                {%else%} <br/>
                        <input type="submit" value="Habilitar" />
                                {%endif%}
                                {%endif%}
                                {% endfor %}
                    </form>
                </td>
                <td align="center">
                        <div id="zs6"></div>
                </td>
            </tr>
            <tr>    
                <td colspan="3" bgcolor="#ff8080">Zona 7 (Julián Estévez hasta Rot.Jenaro de la Fuente-Túnel Martínez Garrido)</td>
                <td align="center">
                    <div id="zv6"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="7" type="checkbox" />
                                {% for i in zone %}
                                {% if i.id == 7 %}
                                {% if i.****_pet == True %}
                         <img width="40px" src="/static/img/check.png"> <br />
                         <input type="submit" value="Deshabilitar"/>
                                {%else%} <br/>
                        <input type="submit" value="Habilitar" />
                                {%endif%}
                                {%endif%}
                                {% endfor %}
                    </form>
                </td>
                <td align="center">
                        <div id="zs7"></div>
                </td>
            </tr>
            <td colspan="3" bgcolor="#ff9999">Zona 8 ( Rot.Jenaro de la Fuente-Túnel Martínez Garrido hasta Julián Estévez)</td>
                <td align="center">
                    <div id="zv8"></div>
                </td>
                <td align="center">
                    <form action="/pet_****/" method="GET">
                            {% csrf_token %}
                         <input hidden checked name="zone_id" value="8" type="checkbox" />
                                {% for i in zone %}
                                    {% if i.id == 8 %}
                                        {% if i.****_pet == True %}
                         <img width="40px" src="/static/img/check.png"> <br />
                         <input type="submit" value="Deshabilitar"/>
                                        {%else%} <br/>
                        <input type="submit" value="Habilitar" />
                                        {%endif%}
                                    {%endif%}
                                {% endfor %}
                    </form>
                </td>
                <td align="center">
                        <div id="zs8"></div>
                </td>
            </tr>
            <tr>    

        </table>
    </div>


        <legend><br><br> </legend>
        <div class="footer" style="text-align: right;">

            <a href="http://www.ctag.com"><img src="/static/img/CTAG-logo.png" width="200px" height="100px"/></a>
            <a href="http://www.grupoetra.com"><img src="/static/img/****-logo.png" width="116px" height="100px"/></a>
            <a href="http://www.****.es"><img src="/static/img/vitrasa-logo.png" width="134px" height="100px"/></a>
            <a href="http://hoxe.vigo.org"><img src="/static/img/vigo-logo.png" width="100px" height="100px"/></a>
        </div>

    </div> <!-- /container -->

    <!-- Javascript -->
    <!-- Placed at the end of the document so the pages load faster -->


<script type="text/javascript">


function sync_****(id){
    $.ajax({    
     url: "/vitrasa_state/",
     type:"GET",
     data: {
       id: id,
     }
    ,success: function( data ) {
        id="#zv"+id;

         $(id).html(data);

     }
   });

}

function sync_pet(id){
    $.ajax({    
     url: "/traffic_ligths_state/",
     type:"GET",
     data: {
       id: id,
     }
    ,success: function( data ) {
        id="#zs"+id;

         $(id).html(data);

     }
   });

}
sync_vitrasa(1);
sync_pet(1);    

/*setInterval("sync_vitrasa(1)",10000);
setInterval("sync_vitrasa(2)",10000);
setInterval("sync_vitrasa(3)",10000);
setInterval("sync_vitrasa(4)",10000);
setInterval("sync_vitrasa(5)",10000);
setInterval("sync_vitrasa(6)",10000);   
setInterval("sync_vitrasa(7)",10000);
setInterval("sync_vitrasa(8)",10000);




setInterval("sync_pet(1)",10000);
setInterval("sync_pet(2)",10000);
setInterval("sync_pet(3)",10000);
setInterval("sync_pet(4)",10000);
setInterval("sync_pet(5)",10000); 
setInterval("sync_pet(6)",10000);
setInterval("sync_pet(7)",10000);
setInterval("sync_pet(8)",10000); 
*/
</script>

    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/js/bootstrap-datetimepicker.min.js"></script>
    <script src="/static/js/openLayers/OpenLayers.js"></script>

    <script type="text/javascript">
        $(function() {
            $('#datetimepicker').datetimepicker({
                language: 'pt-BR'
            });
        });

        var options = {
        controls: [
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar(),
            new OpenLayers.Control.Attribution()
        ]
        };

        var map = new OpenLayers.Map("map", options);           
        map.addLayer(new OpenLayers.Layer.OSM());
        var center = new OpenLayers.LonLat(-8.7181,42.2265);
        center.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
        map.setCenter(center,14);

        var markers = new OpenLayers.Layer.Markers( "Markers" );
        markers.id = "Markers";
        map.addLayer(markers);

        map.events.register("click", map, function(e) {
            if ($('#addMarkerSelected').is(":checked")) {
                var position = map.getLonLatFromPixel(e.xy);
                var positionESPG = map.getLonLatFromPixel (e.xy).transform (map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
                $('#id_lat_position').val(positionESPG.lat);
                $('#id_lon_position').val(positionESPG.lon);
                var size = new OpenLayers.Size(32,32);
                var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
                var icon = new OpenLayers.Icon('/static/img/newMarker.png', size, offset);   
                var markerslayer = map.getLayer('Markers');
                while(markerslayer.markers.length > 0){
                    markerslayer.removeMarker(markerslayer.markers[0]);
                } 
                markerslayer.addMarker(new OpenLayers.Marker(position,icon));
            }
        });

        eventPositions = {{road_events_json|safe}};

        if (eventPositions.length > 0) {
            var eventMarkers = new OpenLayers.Layer.Markers( "Events" );
            eventMarkers.id = "Events";
            map.addLayer(eventMarkers);
            var eventMarkerslayer = map.getLayer('Events'); 
            for (var i= 0; i < eventPositions.length; i++) {
                var eventPosition = new OpenLayers.LonLat(eventPositions[i][1],eventPositions[i][0]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
                var eventSize = new OpenLayers.Size(24,24);
                var eventOffset = new OpenLayers.Pixel(-(eventSize.w/2), -eventSize.h);
                var eventIcon = new OpenLayers.Icon('/static/img/alertMarker.png', eventSize, eventOffset);  
                eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition, eventIcon));
            }
            eventMarkerslayer.setVisibility(false);
            $( "#visibilityEvents" ).change(function() {
                if ($('#visibilityEvents').is(":checked")) {
                    eventMarkerslayer.setVisibility(true);
                } else {
                    eventMarkerslayer.setVisibility(false);
                }
            });
        }           

        $(".olControlAttribution").css("bottom","-1.5em");

    </script>
    {% endblock %}  

1 个答案:

答案 0 :(得分:0)

我已使用此功能解决了问题:

window.onload = function() {
            sync_pet(2);
            sync_vitrasa(2);
            sync_pet(1);
            sync_vitrasa(1);
            sync_pet(3);
            sync_vitrasa(3);
            sync_pet(4);
            sync_vitrasa(4);
            expire_pet(1);
            expire_pet(2)
            expire_pet(3)
            expire_pet(4)
    };

但是,我仍然不知道你必须这样做才能在页面加载时调用javaScript函数。感谢