Passing objects from Django to Javascript DOM

前端 未结 14 1126
野的像风
野的像风 2020-12-04 21:26

I\'m trying to pass a Query Set from Django to a template with javascript.

I\'ve tried different approaches to solve this:

1. Normal Approach - Javas

14条回答
  •  春和景丽
    2020-12-04 22:14

    Ok, I found the solution!

    Mostly it was because of not quoting the results. When Javascript was trying to parse the object this wasn't recognized as string.

    So, first step is:

    var js_list = {{django_list}}; 
    

    changed to:

    var js_list = "{{django_list}}";
    

    After this I realized that Django was escaping characters so I had to replace them like this:

     var myJSONList = (("{{json_list}}").replace(/&(l|g|quo)t;/g, function(a,b){
                    return {
                        l   : '<',
                        g   : '>',
                        quo : '"'
                    }[b];
                }));
    
     myData = JSON.parse( myJSONList );
    

    Note: I tried to avoid escaping characters from Django using this:

    var js_list = "{{json_list|safe}}"; 
    

    But this doesn't work because it gets confused with the quotes.

    Finally I found a way to avoid the logic on the backend of converting to JSON before sending it to Javascript:

    var myDjangoList = (("{{django_list |safe}}").replace(/&(l|g|quo)t;/g, function(a,b){
                return {
                    l   : '<',
                    g   : '>',
                    quo : '"'
                }[b];
            }));
    
    myDjangoList = myDjangoList.replace(/u'/g, '\'')
    myDjangoList = myDjangoList.replace(/'/g, '\"')
    
    myData = JSON.parse( myDjangoList );
    

    I'm sure this can be improved, I let this to you ;)

    Thanks for your answers

    Hope it helps to someone else!

提交回复
热议问题