如何从我的Django视图&url和console获取响应。使用Javascript在我的Django模板(home.html)中记录响应

2024-04-16 21:10:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试在my home.html模板中从我的视图中console.log Json(响应),但没有成功。这是我的密码:

视图.py

def Tweets_view(request, *arg, **kwargs):
    qs = Tweets.objects.all()

    for x in qs:
        tweet_list = { 'id': x.id, 'content': x.content }
        context = { 'response': tweet_list }

    return JsonResponse(context)

url.py

from django.contrib import admin
from django.urls import path
from tweets.views import Tweets_view_id, Tweets_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('tweets', Tweets_view),            #N.B This is the URL I'm trying to access.
    path('tweets/<int:tweet_id>', Tweets_view_id)
]

home.html

{% extends './base.html' %}

{% block content% }
    <div id="tweets">
        LOADING ...
    </div>

    <script>
        
        const tweetsElement = document.getElementById("tweets")
        const xhr = new XMLHttpRequest()
        const method = "post"
        const url = "/tweets"
        const responseType = "json"

        xhr.responseType = responseType
        xhr.open(method, url)
        xhr.onload = function () {
            const serverResponse = xhr.response
            var listedItems = serverResponse.response
            console.log(listedItems)
        }

        xhr.send()

    </script>
{% endblock content% }

我的浏览器(在控制台中不显示任何内容)

This is the link to the my browser display image. No data displays in my console.


Tags: pathfromimportviewidurlresponsemy
1条回答
网友
1楼 · 发布于 2024-04-16 21:10:26

const serverResponse前面放一个console.log以查看是否输入了函数xhr.onload

试着改变你的想法 const serverResponse = xhr.responseconst serverResponse = this.response

(同时记录console.log以查看发生的情况)

source

相关问题 更多 >