我想在后端使用 ajax 和 django 實時獲取訊息,我已經撰寫了發送訊息的邏輯并且它正在作業,但我想立即收到一條訊息,另一個用戶向我發送訊息而無需重繪 頁面,我嘗試使用 ajax 間隔,但似乎我不知道如何在 ajax 中正確使用間隔和 forloop,我應該怎么做才能達到我想要的結果?
更新了圖片
如何在訊息中附加個人資料圖片、個人資料模型的全名和發送訊息的日期。

uj5u.com熱心網友回復:
好吧,我了解您要達到的目標。您正在嘗試使用 django 制作一個聊天系統,并且您正在使用 ajax。但問題是 ajax 主要用于發出異步請求和 api 請求,而 ajax 僅使用 http 請求進行資料傳輸。您需要為聊天系統建立雙向且長期運行的連接。
您正在做的事情可以通過 django 通道和 django 異步(更具體地說是 asgi.py)輕松完成。
Django 頻道非常適合創建實時系統(聊天、通知等)。
轉到此 [鏈接][1] 了解 django 頻道并制作自己的聊天系統。而且我的 github 中有自己的聊天系統。只需克隆 [this][2] 存盤庫。在此檔案夾中運行終端并 (pip install -r requirements.txt) 安裝要求(更好地使用虛擬環境),然后只為檔案運行服務器。您將使聊天系統完全正常作業。
如果您想通過 json 資料或 api 發送影像。您必須使用 base64 編碼器將其轉換為 utf-8 格式。
編碼
# you get the image , say image = instance.profile.image (var image)
# in your consumers.py ( or views.py )
import base64
coneverted_image = base64.b64encode(instance.profile.image.read()).decode("utf-8")
在你的 html
<!-- js file ( where you get the data -->
image = json_data.image()
<!-- in html append your data in chat system -->
<img src = json_data.image>
這將完成你的作業。[1]:https ://channels.readthedocs.io/en/latest/tutorial/part_1.html [2]:https ://github.com/omkashyap007/RealTimeChatApp
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498253.html
標籤:javascript jQuery django 阿贾克斯
上一篇:驗證后提交Ajax表單
