2👍
Have your view just return HTML suitable for your div, not a complete page.
For example, if your http://127.0.0.1:8000/result/
URL is only intended to be used from your AJAX call, then have the view for that URL just render a template without the HEAD, BODY tags etc.
You might have a template something like this:
<ul>
<li>
{{ object.value }}
</li>
<ul>
Note that is doesn’t extend from base.html
or any other template so when the template is rendered, only the template contents you’ve specified are rendered. There is nothing stopping a user from hitting your URL though, in which case the results returned will not be valid HTML for display in a browser.
There are alternatives. You could serve out the data from your server using JSON in the AJAX response and build up the DOM from the JSON data. Or, you could allow the full page to be served as it is now, and use jQuery to replace the contents of your div with only a subsection of the returned page, something like this:
$('#result-div').load(URL + ' #container-div');
The jQuery load() function allows you to specify a fragment of the loaded HTML to insert into your div. In the above example, the contents of the #container-div
element in the served HTML would be inserted into the #result-div
. The remainder of the served HTML will be discarded.