【问题标题】:Django is not rendering data when using ajaxDjango在使用ajax时不呈现数据
【发布时间】:2020-01-23 18:12:40
【问题描述】:

我的 template.html 中有一个简单的代码:

    <div>
        <input type="button" id="buttonId" value="Show Data">  
    </div>
    <script>
        $('#buttonId').click(function() {    
            $.ajax({
                method: 'POST',
                data: {
                    csrfmiddlewaretoken: csrf_token,
                    click: true
                },
                success: function(response){
                    console.log(response) // it is a HTML, not my data
                }
            });
        });
    </script>
    {{results}} 

在我看来.py:

    if request.POST.get('click', False):
        ... #here I get finalresults
        return render(request, 'template.html', context={
            'results': finalresults
        })

当我按下按钮时,脚本运行。所以我知道按下按钮后,finalresults 有内容,但是这个内容并没有到达 HTML 模板。

我做错了什么?

【问题讨论】:

    标签: javascript python html django ajax


    【解决方案1】:

    console.log(response) // 这是 HTML,不是我的数据

    您正在获取 HTML,因为您正在渲染整个模板。

    我想你只想返回results。在这种情况下,只需更改:

    return render(request, 'template.html', context={
        'results': finalresults,
    })
    

    收件人:

    from django.http import JsonResponse
    ...
    ...
    return JsonResponse(
        {'results': finalresults},
    )    
    

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多