How to return a dictionary in python django and view it in javascript?

I return this in my opinion:

    data = {'val1' : 'this is x', 'val2' : True}
    return HttpResponse(data)

I want to use this information in a dictionary in my javascript. A view like this:

            function(data) {
                if (data["val2"]) {
                    //success
                    alert(data["val1"]);
                }
            }

However, my javascript is not working. There are no popup warnings, and I know that the dictionary has information when it leaves my python view.

How can I read this information in my JS?


Ok, so the answer for the view is simplejson.dumps (data). Now, when I make a warning (data) in my JS on my template, I get {'val1': 'this is x', 'val2': True} . Now, how can I manage the second part of a question that reads values ​​such as

        function(data) {
            if (data["val2"]) {
                //success
                alert(data["val1"]);
            }
        }

UPDATE: Simplejson.dumps(data) . javascript . , .

var myObject = eval('(' + myJSONtext + ')');
+5
4

:

import json
data = {'val1' : 'this is x', 'val2' : True}
return HttpResponse( json.dumps( data ) )
+11

JSON - ( XML).

python:

    import json
    data = {'val1': "this is x", 'val2': True}
    return HttpResponse(json.dumps(data))

javascript:

    function (data) {
        data = JSON.parse(data);
        if (data["val2"]) {
            alert(data["val1"]);
        }
    }
+6

Just specify mimetype type in HttpResponse

    return HttpResponse(
                        json.dumps({"status":False, "message":"Please enter a report name."}) ,
                        mimetype="application/json"
                        )
+1
source

All Articles