【问题标题】:Jquery .load() does not work within Django templateJquery .load() 在 Django 模板中不起作用
【发布时间】:2015-09-19 19:43:58
【问题描述】:

我想做的是在模板中呈现一个 html“a”文件。并使用 jquery .load() 在这个 a.html 中嵌入其他 html 文件。但我的以下代码失败了。

以下是我的a.html内容:

<html>
 <head>
  {% load staticfiles %}
   <script type="text/javascript" src="{% static "js/jquery-1.10.2.js" %}" />
   <script>
   $(function(){
     $("#includeContent").load("abc.html");
   });
   </script>
 </head>
 <body> 
   <div id="includeContent"></div>  
 </body>
</html>

以下是我的abc.html:

<html>
<body>
<!-- Hello -->
 <p>Hello world </p>
</body>
</html>

以下是我的应用树:

- App:
  views.py
  models.py
  - static
    -js:
     jquery-1.10.2.js
  - template:
    a.html
    abc.html

在 Firebug 调试器中,我可以看到 jquery-1.10.2.js 的源代码,所以我认为 jquery 脚本包含成功。

我想嵌入到 a.html 中的 abc.html 应该显示“Hello world” 但是加载 a.html 后我什么都看不到。

有没有办法解决这个问题?

添加“模板”的设置:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]

【问题讨论】:

    标签: jquery python html django django-templates


    【解决方案1】:

    Django 在服务器端工作。它根据请求准备响应。另一方面,jQuery 在客户端工作。所有 jQuery 的事情都发生在用户的浏览器上,load 将简单地向 Django 发出另一个请求。但是 jQuery 无法以任何方式访问 Django 文件,因为用户的浏览器无法访问正确配置的服务器中的任何项目文件(希望是为了安全起见)。

    因此,在您的代码中,jQuery 将请求特定的 url abc.html,因此您需要在您的 urls.py 中分别定义一个或重新考虑您的设计。

    【讨论】:

    • 感谢您指出服务器端和客户端的区别。我认为在我的情况下,jQuery 会向 abc.html 而不是 a.html 发出请求?
    • 在 urls.py 中,我将 url(r'^app/abc/', 'app.views.abc') 添加到 urlpatterns。我在views.py中定义了一个函数来将这个特定的请求呈现给templates/abc.html下的abc.html。好像还是不行……
    • 是的,它会向abc.html发出请求。检查你的代码,因为你可能有一些错误,这是一般的想法。
    【解决方案2】:

    我不确定这种方式是否正确是的,我们可以从静态文件中加载 html 创建一个文件夹“folder_name”作为“/static/folder/name.html”

    $('.modal-body').load(
       '/static/pages/sample.html')
    

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      相关资源
      最近更新 更多