【问题标题】:How do I extract JSON data from a Django view using the JQuery - getJSON function?如何使用 JQuery - getJSON 函数从 Django 视图中提取 JSON 数据?
【发布时间】:2011-09-17 21:51:18
【问题描述】:

假设我在 Django views.py 中有函数 get_a_color

   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 函数?

【问题讨论】:

  • 你到底在问什么?如何在Javascript中获取数组的第一项?

标签: jquery django django-templates django-views


【解决方案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]); });

});

【讨论】:

    猜你喜欢
    • 2014-07-12
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2013-02-01
    • 1970-01-01
    相关资源
    最近更新 更多