4

The thing I want to do is to render a html "a" file in template. And use jquery .load() to embedded other html files in this a.html. But I failed with my following code.

The following is my a.html content:

<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>

The following is my abc.html:

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

The following is my app tree:

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

In Firebug debugger, I can see the source code of jquery-1.10.2.js so I think the jquery script is successfully included.

The abc.html I want to embedded into a.html should show "Hello world" But I cannot see anything after I load the a.html.

Is there a way to fix this?

Add the setting of "Templates":

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',
        ],
    },
},

]

Chang May
  • 165
  • 1
  • 10

2 Answers2

7

Django works at server-side. It prepares a response based on a request. jQuery works at client-side on the other hand. All jQuery things happen on the user's browser, and load will simply make another request to Django. But jQuery is not able to access Django files in any way, as the user's browser is not able to access any of your project files in a properly configured server (hopefully for the sake of security).

Therefore in your code jQuery will make a request for the specific url abc.html, so you need to respectively define one in your urls.py or basically rethink your design again.

Wtower
  • 18,848
  • 11
  • 103
  • 80
  • Thank you for point out the server-side and client-side difference. I think in my case jQuery will make a request to abc.html not a.html? – Chang May Jul 02 '15 at 15:31
  • 1
    In urls.py, I added url(r'^app/abc/', 'app.views.abc'), to urlpatterns. And I defined a function in views.py to render this specific request to abc.html under templates/abc.html. Seems that it is still not working... – Chang May Jul 02 '15 at 15:34
  • 1
    Yes, it will make a request to `abc.html`. Check your code because you might have some error in it, this is the general idea. – Wtower Jul 03 '15 at 08:22
-3

Iam not sure this way is correct yes we can load html from static files create a folder "folder_name " as "/static/folder/name.html"

$('.modal-body').load(
   '/static/pages/sample.html')
Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35