【问题标题】:Handling AJAX response with jQuery $.ajax in Django application在 Django 应用程序中使用 jQuery $.ajax 处理 AJAX 响应
【发布时间】:2012-10-30 08:51:13
【问题描述】:

我正在对服务器进行 ajax 调用,并希望接收一个数组以进行进一步处理。我是一个初学者,对我真正在做什么感到很困惑。下面是我到目前为止想出的一个sn-p。在我尝试处理返回的数据之前,它运行良好。我认为我的问题是我并不真正了解如何形成正确的响应以及如何处理它。

JAVASCRIPT/JQUERY:

var shoppingList = {
    // SOME CODE BEFORE

    'foodIngredients' : function() {
        // Send a list of food ids and receive an array of necessary ingredients. Make the returned array unique.
        $.ajax({
            url: 'http://localhost:8000/ingredients/',
            // ingredients.html template:
            // [{% for item in ingredients %}{% if forloop.last %}{{ item.id }}{% else %}{{ item.id }},{% endif %}{% endfor %}]
            type: 'POST',
            data: JSON.stringify(shoppingList.selectedFoods),
            dataType: 'text',
            cache: 'false',
            success: function(result){
                console.log(result); // [33,85,88,89,91]
                shoppingList.returnedIngredients = result;
                shoppingList.uniqueIngredients = _.unique(shoppingList.returnedIngredients);
                console.log(shoppingList.uniqueIngredients); // [,3,,,8,5,9,1,] <-- NOT OK; Expected [33,85,88,89,91]
            }
    });
    },

    // SOME CODE AFTER
};

成分视图:

def ingredients(request):
    if request.is_ajax():
        ourid = json.loads(request.raw_post_data)
        ingredients = Ingredience.objects.filter(food__id__in=ourid)
        t = get_template('ingredients.html')
        html = t.render(Context({'ingredients': ingredients,}))
        return HttpResponse(html)
    else:
        html = '<p>This is not ajax</p>'      
        return HttpResponse(html)

【问题讨论】:

  • 能把/ingredients/view的代码贴一下吗?
  • @jpic:添加成分视图。
  • @jade:_.unique 是 underscore.js 库中的一个函数:underscorejs.org/#uniq
  • result 是一个字符串,而不是一个数字数组。所以_.unique 正在返回字符串中的唯一字符。您需要使用jSON.Parse 将结果转换为数组。或者在选项中指定dataType: 'json'

标签: javascript jquery python ajax django


【解决方案1】:

result 是一个字符串,而不是一个数字数组。所以 _.unique 返回字符串中的唯一字符。您需要使用jSON.Parse 将结果转换为数组。或者在选项中指定dataType: 'json'

【讨论】:

  • 是的,你是对的。只需指定 ̣̣dataType: 'json' 即可解决问题。我仍然不明白它是如何工作的。 json不应该是key : value格式吗?
  • JSON 可用于编码几乎任何类型的 JavaScript 数据。如果是对象,则为 {key:value, key:value},如果是数组,则为 [element, element, element]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多