2011-06-18 39 views
0

假設我有一個Django的views.py功能get_a_color如何使用JQuery-getJSON函數從Django視圖中提取JSON數據?

from django.utils import simplejson 

    def get_a_color(request): 
     colors = ['red', 'blue', 'yellow'] 
     data = simplejson.dumps(colors) 
     return HttpResponse(data, mimetype='application/javascript') 

如何將提取的顏色「紅色」,例如使用jQuery的$ .getJSON函數?

+0

到底在問什麼在這裏?如何在Javascript中獲取數組的第一項? –

回答

1

不知道你尋找什麼做的,但我把一個快速fiddle共同展示如何讓紅了你返回的JSON數組....

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

});