0

I'm trying to send data results from django to javascript in JSON through an AJAX call. In django I have the below variable

results = {key1:[1,2,3],
           key2:[[name1,lat1,lng1],[name2,lat2,lng2],[name3,lat3,lng3]]}

I can then successfully return a json dump of results I have verified that the data being captured by my javascript ajaxSuccess function is exactly results

I would like the output to be as follows:

var1 = [1,2,3]
var2 = [name1, lat1, lng1]
var3 = [name2, lat2, lng2]
var4 = [name3, lat3, lng3]

What is the best way to parse the results in javascript and should I reformat it some other way in django first?

bcoop713
  • 1,063
  • 5
  • 13
  • 24

3 Answers3

1

Based on your update in your question, here is a jsfiddle with the exact output you are looking for.

http://jsfiddle.net/jhanifen/7RfNs/

And a jsfiddle with a loop using jquery

http://jsfiddle.net/jhanifen/7RfNs/1/

Depending on how you want to parse and use the results, try using jquery each as karthikr stated in the comment

http://api.jquery.com/jQuery.each/

As stated in the jquery docs

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});

Also you can use json.dumps in django, which makes it very easy to output json, see this post

Creating a JSON response using Django and Python

return HttpResponse(json.dumps(response_data), mimetype="application/json")
Community
  • 1
  • 1
jhanifen
  • 4,441
  • 7
  • 43
  • 67
  • That is how I'm getting the results to the .js already. Sorry if that wasn't clear. Does that effect the jquery? – bcoop713 Aug 07 '13 at 02:58
  • Can you give an example of how you would like the output. I think if we had a better idea of what you are trying to accomplish on the client side we could answer your post more specifically – jhanifen Aug 07 '13 at 02:59
  • bcoop713, added a jsfiddle with the exact output your looking for. – jhanifen Aug 07 '13 at 14:59
  • Thanks so much. I had been trying to use JSON.parse but that was breaking everything for some reason. Much appreciated. – bcoop713 Aug 07 '13 at 15:41
  • It's preferable for you to put the relevant portions of the JSFiddle into the answer and keep the JSFiddle as supplementary. That way the next person that visits this question does not have to worry about whether or not JSFiddle is up. – George Stocker Aug 07 '13 at 17:09
1

You can use JSON.parse(results) and or eval(results) in javascript to parse the result.

Ashis Kumar
  • 6,494
  • 2
  • 21
  • 36
1

Just use ajax():

$.ajax({ 
    type: 'GET', 
    url: 'http://example/foo/', 
    dataType: 'json',
    success: function (data) { 
        console.log(data); // do anything you want with your parsed data
    }
});
dan-klasson
  • 13,734
  • 14
  • 63
  • 101