开发者

How do I extract JSON data from a Django view using the JQuery - getJSON function?

开发者 https://www.devze.com 2023-03-14 01:50 出处:网络
Assuming that I have function get_a_color in a Django views.py: from django.utils import simplejson def get_a_color(request):

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]); });

});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号