无法使用ajax调用django视图
我想从客户端调用 django 视图,该视图将在 html 页面上显示来自模型的所有消息
AJAX 函数
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/load_with_room_name/{{room_name}}/",
success: function(response){
console.log(response);
$("#display").empty();
},
error: function(response){
alert('An error occured')
}
});
},1000);
})
</script>
django 视图函数
def load_with_room_name(request,room_name):
try:
current_user = Account.objects.get(email=str(request.user))
chat_room = ChatRoom.objects.get(room_name=room_name)
if chat_room.room_user_1 == current_user or chat_room.room_user_2 == current_user:
print(current_user)
return redirect('room',room_name,current_user.username)
else:
return redirect('chat')
except Exception as e:
log_exception(request,e,view_name="load_with_room_name")
return render(request,"error.html")
django urlpattern 对于上述视图
urlpatterns = [ path('load_with_room_name/<str:room_name>',views.load_with_room_name,name='load_with_room_name'),
]
I want to call the django view from client side that will display all the messages from the models on the html page
AJAX function
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/load_with_room_name/{{room_name}}/",
success: function(response){
console.log(response);
$("#display").empty();
},
error: function(response){
alert('An error occured')
}
});
},1000);
})
</script>
django view function
def load_with_room_name(request,room_name):
try:
current_user = Account.objects.get(email=str(request.user))
chat_room = ChatRoom.objects.get(room_name=room_name)
if chat_room.room_user_1 == current_user or chat_room.room_user_2 == current_user:
print(current_user)
return redirect('room',room_name,current_user.username)
else:
return redirect('chat')
except Exception as e:
log_exception(request,e,view_name="load_with_room_name")
return render(request,"error.html")
django urlpattern for the above view
urlpatterns = [ path('load_with_room_name/<str:room_name>',views.load_with_room_name,name='load_with_room_name'),
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然您已经通过在 django 项目中正确访问它来测试它的工作原理,但我发现您只需要添加完整路径,如下所示
while you have already tested that it works by accessing it correctly in your django project only I see that you would only need to add the full path as follows
将 url 更改为
以便使用 django url-pattern 并注意原始代码中的尾部斜杠。您的 url 模式中没有尾部斜杠!
change url to
in order to use the django url-pattern and be aware of the trailing slash in your original code. There is no trailing slash in your url-pattern!