开发者

Is content from AJAX call added to Django context variable

I am using the JQuery load function to load part of my page. Can I access the variables开发者_C百科 from that page in the page that loads it. e.g.

  • Page A uses JQuery load function to load B

  • Page B loads and sets a variable in context called pageB_var which holds a django object

  • Page A can then access this variable by doing {{pageB_var}} since it was added to the context

If not what is the best way of doing this?

Thanks


No. Page B's rendering context is irrelevant and unreachable by the time you get B's response.

Here's what happens: Page A is rendered in the server. during this time, its context exists. when the server is done rendering it, it sends the rendered page to the client. the client web browser then runs the javascript including your jquery load() to call the server again and tell it to render B. at this point the process that rendered page A doesn't exist anymore, so for page B to send stuff to page A's rendering you would have to make time travel....

The way to do this, is for page B to return a JSON object, and then use the (javascript) callback function given to load() to render changes to the page based on this JSON response from B.


It sounds like you're using an asynchronous request to update part of a page, receiving a partial HTML response and replacing part of the markup of your page with this response.

You've found that this obviously limits you to updating information contained within that partial page.

Consider instead providing a JSON response to your asynchronous request, containing all the information you need, and then updating the necessary HTML in any part of the page by manipulating the DOM client-side, with JavaScript. Think of the JSON as being your context for this purpose.


Once page A is sent to the browser it's mostly fixed in memory. You'd have to use the DOM functions in JavaScript in order to modify what it shows. Having said that, you could return JSON from the view for the call to page B and then decode it and insert it into page A.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜