在Jquery中定义Django上下文变量给我错误? [英] Defining Django context variable in Jquery giving me error?

查看:229
本文介绍了在Jquery中定义Django上下文变量给我错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的jquery脚本中使用一个django上下文变量。

I am trying to use a django context variable in my jquery script.

首先,这个工作:

index.html

<head>
    <script type="text/javascript">
        var page_size = {{page_obj.paginator.num_pages}};
    </script>

    <script type="text/javascript" src="{% static 'js/paginate.js' %}"></script>
</head>

js / paginate.js

$(document).ready( function() {
    alert(page_size);                           //THIS WORKS!!!
});






但是,我不希望用户能够查看我的变量,所以我只是在我的paginate.js文件中添加了全局变量声明:

However, I didn't want the users to be able to be view my variables so I simply added the global variable declaration in my "paginate.js" file:

index.html

<head>
    <script type="text/javascript" src="{% static 'js/paginate.js' %}"></script>
</head>

js / paginate.js

var page_size = {{page_obj.paginator.num_pages}};              //Exactly the same as the above!!

$(document).ready( function() {
    alert(page_size);                           //ERROR!!!
});



奇怪的是,这给了我一个错误:


Strangely enough, this gives me an error:

SyntaxError: invalid property id
    var page_size = {{page_obj.paginator.num_pages}};

我不知道为什么第一个工作,而第二个给我一个错误,因为他们是完全一样...也许因为我是第二个在Jquery中声明..?任何想法?

I have no idea why the first one works while the second one gives me an error, because they are exactly the same... Maybe because I'm second one is declaration in Jquery..?? Any idea??

谢谢..

推荐答案

TL; DR



您不能将变量传递给静态文件,因为它们不会被Django模板处理器解析。

TL;DR

You can't pass a variable to a static files because they aren't parse by the Django template processor.

您的第一个例子是因为您设置 {{page_obj.paginator .nu​​m_pages}} 在您的模板中,将被解析并转换成一个数字。当您使用Django返回模板(通过任何 render 方法)时,只会渲染模板。您的模板中链接的CSS和Javascript称为静态文件:这意味着它们是不会被Django模板处理器读取的资源。

Your first example works because you set the {{ page_obj.paginator.num_pages }} in your template, which will be parsed and transform into a number. When you're returning a template with Django (through any render method), only the template will be rendered. CSS and Javascript linked in your template are called static files: that means they're ressources which will not be read by the Django template processor.

想象一下,您要将变量插入到页面中的img中。有什么意义吗?没有?但是,这是一样的行为。

Imagine that you want to insert your variable in an img in your page. Does it makes any sense? No? However, it's the same behavior.

您可以通过Javascript文件中的AJAX请求获取数据

You can get the data either via an AJAX request in your Javascript file (warning: a bit overkill for your case here), or using your first method.

相关主题:

  • Passing Python Data to JavaScript via Django
  • Passing parameters to the Javascript code on a page using django templates?

这篇关于在Jquery中定义Django上下文变量给我错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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