如何在不重新加载页面更新Django的页面?页面、加载、如何在、Django

2023-09-11 00:48:13 作者:胯下狙击手

我的Django应用程序显示数据库中的数据。没有用户干预该数据的变化,即在幕后。每当它改变,我想网页更新变化的部分没有一个完整的页面重载。

My Django app displays data from a database. This data changes without user intervention, i.e. behind the scenes. Whenever it changes, I would like the webpage to update the changed sections without a full page reload.

显然AJAX浮现在脑海。当页面加载最初(或手动,完全重新加载以后),渲染模板加载又运行在window.onload =更新一个JavaScript(全),更新(...)引发了一些XMLHTT的prequests这再次返回被转换为HTML片段的相应部分的数据。一切工作正常。在初始页面加载。

Obviously AJAX springs to mind. When the page is loaded initially (or manually, fully re-loaded later on), the rendered template loads a JavaScript that runs window.onload = update("all"), update(...) in turn triggers a number of XMLHTTPRequests which again return data that gets transformed into HTML pieces for the corresponding sections. All works fine. At the initial page load.

现在我发现自己活在一个Python函数,节省了一个新的对象到数据库中。

Now I find myself in a Python function that saves a new object to the database.

我如何让浏览器运行update()?

How do I tell the browser to run update(...) ?

我是否需要以某种方式手动发出一个请求映射到一个视图这反过来又使得它包含的JavaScript code运行update(...)模板的URL ???噢,我的!

Do I need to somehow manually issue a request to a url that is mapped to a view which in turn renders a template that contains the JavaScript code to run update(...) ??? Oh my!

我觉得我不是按照通常的做法。 也许我只是站在将在面前的难题。

I feel like I'm not following the usual approaches. Maybe I'm just standing to close in front of the problem.

谁能帮我?

推荐答案

两种方法:

刚刚更新的数据库,并等待下一个AJAX查询。这意味着它应该定期做查询,你就会有即时性和服务器负载之间的平衡。它帮助一点,如果你可以做一个廉价的查询,只验证是否出现了更新。也许是为了查收依靠的将数据库

just update the database and wait until the next AJAX query. that means it should do the query periodically, you'll have to balance between immediacy and server load. it helps a little if you can do a cheap query to just verify if there has been an update. maybe make that check rely only on memcached instead of going to the DB

使用彗星。总之:在客户端做一个AJAX查询要求的更新。该服务器发现没有更新,所以也没有回答。相反,连接保持打开很长时间。最终无论是更新来了,服务器终于回答,或者客户端超时,并杀死连接。在这种情况下,客户端应该立即重新发出查询以保持等待更新

use comet. In short: the client does an AJAX query asking for the update. the server sees there's no update, so it doesn't answer. instead, the connection is kept open for a long time. eventually either the update comes and the server finally answers, or the client times out and kill the connection. in that case, the client should immediately reissue the query to keep waiting for the update.