Assuming that I have function get_a_color
in a Django views.py:
from django.utils import simplejson
def get_a_color(request):
colors = ['red', 'blue', 'yellow']
data 开发者_如何学运维= simplejson.dumps(colors)
return HttpResponse(data, mimetype='application/javascript')
How will I extract the color 'red' for example using the jQuery $.getJSON function?
Not sure exactly what you're looking to do, but I put a quick fiddle together to show how to get red out of your returned JSON array....
$(document).ready(function(){
var colors = {colors : ['red','yellow','blue']};
var colorjson = JSON.stringify(colors);
alert(colorjson);
/*
$.ajax({
type:'POST',
url: '/echo/json/',
cache: false,
success: function(d) { alert(d.colors[0]);},
error: function() { alert('boo');},
data: { json : colorjson }
});
*/
$.post('/echo/json/', { json: colorjson }, function(d) { alert(d.colors[0]); });
//you would do the same thing with $.getJSON(...), if it were supported by jsFiddle....
//$.getJSON('/echo/json/', { json: colorjson }, function(d) { alert(d.colors[0]); });
});
精彩评论