使用Flask/Python的jQuery导航栏

0 投票
1 回答
530 浏览
提问于 2025-04-18 00:02

我用Dreamweaver做了一个简单的网页,里面有一个用jquery做的导航栏。这个网页在我的树莓派上用Flask运行,但导航栏现在不工作了。

HTML代码:

<table width="100%" height ="100%" border="0">
   <tr>
     <td width="120px" valign="top">
       <ul  id="Navigation" class="nav">
        <li id="home" ><a data-site="home" href=""><br><img src="{{ url_for('static',filename='icons/Home.png')}}" width="40" height="40"><br> Home</a></li>
        <li id="light"><a data-site="light" href=""></a></li>
        <li id="htpc"><a data-site="htpc" href=""></a></li>

      </ul>

     </td>

     <td class="content" valign="top" ></td>
   </tr>
 </table>

jquery:

 <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function(){ 

            $(".content").load("{{ url_for('static', filename='home.html')}}");
            $('.nav a').click(function(e){              
                e.preventDefault();                
                var site = $(this).data('site'); 

                site = site + '.html';                

                $(".content").load(site); 
            });
        });
</script>

我用url_for函数替换了一些链接,这个方法对图片很有效。我把home.html弄好了,但其他的还是不行。当我点击

  • 元素“light”时,出现了404错误,提示“light.html not found”。我知道路径可能错了,但我该怎么简单地解决这个问题呢?

  • 1 个回答

    0

    搞定了!

    在*.py文件中需要有一个@app.route

    (...)
    @app.route("/light", methods=['GET'])
    def light():
        return render_template('light.html')
    (...)
    

    light.html文件必须放在/templates文件夹里。你可以通过"/light"来使用它。我对home.html也是这么做的。也许这不是最好的方法,但它确实能用!

    像这样:

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
    
            $(document).ready(function(){ 
    
                $(".content").load("/home");
                $('.nav a').click(function(e){              
                    e.preventDefault();                
                    var site = $(this).data('site'); 
    
                     site  = '/' + site;                
    
                    $(".content").load(site); 
                });
            });
    </script>
    

    撰写回答