Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm returning this in my view:

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

I want to use this information in the dictionary within my javascript. Kind of like this:

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

However my javascript doesn't work. There is no alert popping up and I know that the dictionary has the information when it leaves my python view.

How can I read this information in my JS?


Ok so the answer for the view is to simplejson.dumps(data). Now when I do an alert(data) in my JS on my template I get {'val1' : 'this is x', 'val2' : True}. Now how can I manage the 2nd part of the question which is read out the values like

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

UPDATE: The simplejson.dumps(data) converts th dictionary into string. So in the javascript you need to convert the string to an object. THis is the easiest but apparently unsafe way.

var myObject = eval('(' + myJSONtext + ')');
like image 284
darren Avatar asked Jun 24 '11 12:06

darren


4 Answers

JSON is easiest way to transfer data(also you can use XML).

In python:

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

In javascript:

    function (data) {
        data = JSON.parse(data);
        if (data["val2"]) {
            alert(data["val1"]);
        }
    }
like image 117
levalex Avatar answered Oct 16 '22 12:10

levalex


Very simply:

import json
data = {'val1' : 'this is x', 'val2' : True}
return HttpResponse( json.dumps( data ) )
like image 28
underrun Avatar answered Oct 16 '22 10:10

underrun


You can not directly use the python object you have to convert it into JSON string first Look into following documentation.

http://docs.python.org/library/json.html also http://www.json.org/

like image 20
Sap Avatar answered Oct 16 '22 11:10

Sap


Just specify the mimetype in HttpResponse

    return HttpResponse(
                        json.dumps({"status":False, "message":"Please enter a report name."}) ,
                        content_type="application/json"
                        )
like image 31
pass-by-ref Avatar answered Oct 16 '22 12:10

pass-by-ref