缺少变量值时 Django 模板中的 Javascript 语法错误 [英] Javascript syntax error in Django Template when variable value is missing

查看:23
本文介绍了缺少变量值时 Django 模板中的 Javascript 语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 AJAX 菜单的 Django 模板(点击不同的菜单项会重新加载页面的一部分).每次菜单点击都会通过 AJAX 调用一个 Django 视图函数,并返回一些要显示在页面上的数据.

I have a Django template with an AJAX menu (where clicking on different menu items reloads a part of the page). Each menu click invokes a Django view function through AJAX and returns some data to be shown on the page.

我只加载主页中所有菜单项所需的所有 JS(因为我了解到 AJAX 在 <div> 和然后使用 eval() 来执行它).由于我只加载了菜单主页上的所有 JS,因此其他菜单选项在开始时显然不存在数据,因为它会在调用相应视图时(单击菜单选项时)稍后出现

I am loading all the JS required for all the menu items in the main page only (as I learnt that it is not a good idea for AJAX to return JS in a <div> and then use eval() to execute it). Since I am loading all the JS on the menu's main page only, the data obviously isn't there for other menu options at start since it will come later when the corresponding view is invoked (when the menu option is clicked)

因此,像下面这样的代码会在控制台上出现语法错误,因为 JS 只在第一次被解析.

Because of that, code like the one below gives a syntax error on the console since JS is parsed the very first time only.

<script> var data = {{se_data|safe}}; </script>

现在我无法使用从视图返回的数据,即使我点击了菜单选项,因为 JS 解析首先失败了.我尝试使用 if 仅在选择相应的菜单选项时执行代码,但这也不起作用,因为解析器只是解析所有内容.

Now I am not able to use the data returned from the view, even after I click the menu options, since the JS parsing failed in the first place. I tried using if to execute the code only when the corresponding menu option is selected but that too does not work since the parser just parses everything.

我一直在尝试不同的方法来解决这个问题,但似乎找不到一种有效的方法来解决这个问题.另一种方法是让视图函数首先只返回所有数据,但我担心菜单选项和返回的数据可能会随着时间的推移而增长,从而延迟主菜单页面的初始加载.

I have been trying different methods to get around the issue but cant seem to find an efficient way to solve this. An alternative could be to have the view function return all the data at first only, but I fear that the menu options and the data returned may grow over time, hence delaying the initial load of the main menu page.

这是ajax菜单的点击功能:

This is the ajax menu's click function:

$(".ent-menu li a").click(function(e) {
    e.preventDefault(); // prevent from going to the page mentioned in href
    // get the href
    var href = $(this).attr("href");

    $("#data_container").load(href, function() {
        load_data(); //this function uses the data variable defined earlier
    });
});

我在加载菜单主页时在控制台中看到的错误:

Error I see in the console when loading the menu's main page:

Uncaught SyntaxError: Unexpected token ;     at line 1110
data = ;

因为数据尚不可用.

推荐答案

如前所述,您应该使用 JSON 将数据从 Python 发送到 JS;使用 JSON.parse() 反序列化数据以在您的 JS 中使用.

As discussed, you should use JSON to send the data from Python to JS; use JSON.parse() to deserialize the data for use in your JS.

这篇关于缺少变量值时 Django 模板中的 Javascript 语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆