使用变量部分在URL中后出现错误“jQuery未定义” - Flask框架

0 投票
2 回答
1589 浏览
提问于 2025-04-18 10:45

这是我的网页架构

Web
|-->static
   |-->css
   |-->js
   |-->img
|-->templates
   |-->test1
   |-->test2
|-->modfunctions
   |-->test1
         |-->main.py
   |-->test2
         |-->main.py

如果我使用像 @app.route('/test2', methods=['GET','POST']) 这样的唯一网址,我的JQuery部分工作得很好。但是当我尝试在网址中添加变量部分,比如 @app.route('module/<data>', methods=['GET','POST']) 时,就出现了错误,提示'jQuery未定义'。

这里我附上了我的代码

from flask import Flask
from flask import render_template, request, redirect

app = Flask(__name__, template_folder='/home/web/templates', static_folder='/home/web/static')

@app.route('module/<data>', methods=['GET','POST'])
def mod_data(data):
    if request.method == 'GET':
        return render_template('test1/page1.html')

    if request.method == 'POST':
        return render_template('test1/page2.html')

if __name__ == "__main__":
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

请帮我找出我的错误,并分享一些解决方案


最终的HTML页面

{% extends "base.html" %}

{% block content %}
<table id="grid-table"></table>
<div id="grid-pager"></div>
{% endblock content%}

{% block js %}
<script type="text/javascript">
    var grid_data = [{'Description':'Core A', 'Mask':'True','Mail':'True', 'Trap':'True'},
                 {'Description':'Core B', 'Mask':'True','Mail':'True', 'Trap':'True'},
                 {'Description':'Core C', 'Mask':'True','Mail':'True', 'Trap':'True'},
                 {'Description':'Core D', 'Mask':'True','Mail':'True', 'Trap':'True'}]

    jQuery(function($) {
        var grid_selector = "#grid-table";
        var pager_selector = "#grid-pager";

        jQuery(grid_selector).jqGrid({
                editurl: 'module/new_data',
                data: grid_data,
                datatype: "local",
                height: "auto",
                colNames:['','Module Description', 'Mask', 'Mail','Trap'],
                colModel:[
                    {name:'myac',index:'', width:80, fixed:true, sortable:true, resize:false,
                     formatter:'actions',
                     formatoptions:{
                        keys:true,
                        delbutton:false,
                        }
                    },
                {name:'Description',index:'Description', width:70, sortable:true, editable: false,formatter: returnHyperLink},
                {name:'Mask',index:'Mask',  width: 20, align: 'center',formatter: 'checkbox', editable: true, edittype: "checkbox", editoptions: { value: 'True:False' }, formatoptions: { disabled: true }},
                {name:'Mail',index:'Mail', width: 20, align: 'center',formatter: 'checkbox', editable: true, edittype: "checkbox", editoptions: { value: 'True:False' }, formatoptions: { disabled: true }},
                {name:'Trap',index:'Trap', width: 20, align: 'center',formatter: 'checkbox', editable: true, edittype: "checkbox", editoptions: { value: 'True:False' }, formatoptions: { disabled: true }},

                ],
                pgbuttons:false,
                pginput: false,
                viewrecords : true,

                width : 510,
                pager : pager_selector,
                altRows: true,

                multiselect: true,
                multiboxonly: true,

                loadComplete : function() {
                    var table = this;
                    setTimeout(function(){
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },

                caption: "Current Settings",
                autowidth: false
                });

                //navButtons
                jQuery(grid_selector).jqGrid('navGrid',pager_selector,
                {   //navbar options
                    edit: true,
                    editicon : 'icon-pencil blue',
                    add: false,
                    addicon : 'icon-plus-sign purple',
                    del: false,
                    delicon : 'icon-trash red',
                    search: true,
                    searchicon : 'icon-search orange',
                    refresh: true,
                    refreshicon : 'icon-refresh green',
                    view: true,
                    viewicon : 'icon-zoom-in grey',
                },
                {
                    //edit record form
                    closeAfterEdit: true,
                    recreateForm: true,
                    beforeShowForm : function(e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //new record form
                    closeAfterAdd: true,
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm : function(e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //search form
                    recreateForm: true,
                    afterShowSearch: function(e){
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                        style_search_form(form);
                    },
                    afterRedraw: function(){
                        style_search_filters($(this));
                    },
                    multipleSearch: true,
                },
                {
                    //view record form
                    recreateForm: true,
                    beforeShowForm: function(e){
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    }
                });

        function style_edit_form(form) {
            //update buttons classes
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-primary').prepend('<i class="icon-ok"></i>');
            //buttons.eq(1).prepend('<i class="icon-remove"></i>')

            buttons = form.next().find('.navButton a');
            buttons.find('.ui-icon').remove();
            buttons.eq(0).append('<i class="icon-chevron-left"></i>');
            buttons.eq(1).append('<i class="icon-chevron-right"></i>');
        }

        function style_search_filters(form) {
            form.find('.delete-rule').val('X');
            form.find('.add-rule').addClass('btn btn-xs btn-primary');
            form.find('.add-group').addClass('btn btn-xs btn-success');
            form.find('.delete-group').addClass('btn btn-xs btn-danger');
        }

        function style_search_form(form) {
            var dialog = form.closest('.ui-jqdialog');
            var buttons = dialog.find('.EditTable')
            buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet');
            buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt');
            buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search');
        }
        function beforeEditCallback(e) {
            var form = $(e[0]);
            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_edit_form(form);
        }
        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
                {
                'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
                'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
                'ui-icon-seek-next' : 'icon-angle-right bigger-140',
                'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
            };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
            if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
            })
        }
        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({container:'body'});
            $(table).find('.ui-pg-div').tooltip({container:'body'});
        }
{% endblock js %}   

基础.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>

<body>
    {% block content %} {% endblock content%}
        <!-- basic scripts -->


    <script type="text/javascript">
        window.jQuery || document.write("<script src='static/js/jquery-2.0.3.min.js'>"+"<"+"/script>");
    </script>

    <script type="text/javascript">
        if("ontouchend" in document) document.write("<script src='static/js/jquery.mobile.custom.min.js'>"+"<"+"/script>");
    </script>
    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"/>
    <script src="{{ url_for('static', filename='js/typeahead-bs2.min.js') }}"></script>
    <!-- page specific plugin scripts -->
    <script src="{{ url_for('static', filename='js/modal/jquery.simplemodal.js') }}"></script>
    <script src="{{ url_for('static', filename='js/modal/osx.js') }}"></script>

    <script src="{{ url_for('static', filename='js/date-time/bootstrap-datepicker.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jqGrid/jquery.jqGrid.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jqGrid/i18n/grid.locale-en.js') }}"></script>

    <!-- sedona scripts -->
    <script src="{{ url_for('static', filename='js/sedona-elements.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/sedona.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jqGrid/jquery.jqgrid.functions.js') }}"></script>


    {% block js %}{% endblock js %}

</body>

2 个回答

0

我觉得在你的JS代码块里,你可能覆盖了你的jQuery抓取。试着在你的{% block js %}的最上面加一个{{ super() }}。不过,这其实只是我的猜测,因为我之前也犯过这个错误。

另外,根据你的评论来看,jQuery是在你的JavaScript运行之后加载的。在你继承的模板里,定义jQuery的代码块是在{% block js %}之前,还是之后呢?

0

问题出在你引用jQuery库的方式上:

window.jQuery || document.write("<script src='static/js/jquery-2.0.3.min.js'>"+"<"+"/script>");

static/js/jquery-2.0.3.min.js是一个相对网址,这意味着它会根据当前文档的网址而变化。例如,如果你在一个页面/foo/上,它会尝试加载/foo/static/js/jquery-2.0.3.min.js(但会失败)。你需要使用url_for()这个助手函数来引用jQuery。可以这样做(未测试):

window.jQuery || document.write("<script src='{{ url_for('static', filename='js/jquery-2.0.3.min.js') }}'>"+"<"+"/script>");

撰写回答