简体   繁体   English

AJAX 请求 Django 视图提取数据但列表未填充

[英]AJAX request to Django view pulls data but list not populating

Trying to populate a side bar with session status from api server.尝试使用来自 api 服务器的 session 状态填充侧栏。 Having trouble following a modified example shown here:遵循此处显示的修改示例时遇到问题:

How to dynamically generate html list from json array received via ajax call? 如何从通过 ajax 调用接收的 json 数组动态生成 html 列表?

I'm able to get the console to log the dict values but when I try to populate a list following the example it fails to show anything on the page.我可以让控制台记录 dict 值,但是当我尝试按照示例填充列表时,它无法在页面上显示任何内容。 I also don't see any dev console errors.我也没有看到任何开发控制台错误。

HTML: HTML:

<div id="sessionstatuslist">
        </div>

Ajax Function: Ajax Function:

function sessionStatus(){
    var _url = "ajax/get_sessionstatus";
    var request = $.ajax({
        "url": _url,
        dataType : 'json',
        type : 'GET',
        data: {},
    success: function (data) {
                var list_html = "<ol>";
                for( var i=0; i <data.length; i++) {
                   list_html += "<li>" + data[i] + "</li>";
                 }
                list_html += "</ol>"
                $("#sessionstatuslist").html(list_html);
            },
            error: function(data) {
                console.log('there was a problem');
            }
         });
         return false;    
     };

View:看法:

def Getsessionstatus(request):
    sessionstatus_list = {'session 1': 'running', 'session 2': 'idle',}
    data = sessionstatus_list
return JsonResponse(data)

The fix was very easy,修复非常简单,

function sessionStatus(){
    var _url = "ajax/get_sessionstatus";
    var request = $.ajax({
        "url": _url,
        dataType : 'json',
        type : 'GET',
        data: {},
    success: function (data) {
                var list_html = "<ol>";
                data = Object.values(data);
                for( var i=0; i <data.length; i++) {
                   list_html += "<li>" + data[i] + "</li>";
                 }
                list_html += "</ol>"
                $("#sessionstatuslist").html(list_html);
            },
            error: function(data) {
                console.log('there was a problem');
            }
         });
         return false;    
     };

Was able to add Object.values() method to enumerate the property values of the array.能够添加 Object.values() 方法来枚举数组的属性值。 It seems to work this way.它似乎以这种方式工作。 There is probably a better way with the Jquery Map() method. Jquery Map() 方法可能有更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM