Javascript 在Django应用程序中使用jQuery$.AJAX处理AJAX响应

Javascript 在Django应用程序中使用jQuery$.AJAX处理AJAX响应,javascript,jquery,python,ajax,django,Javascript,Jquery,Python,Ajax,Django,我正在对服务器进行ajax调用,希望接收一个数组以进行进一步处理。我是个初学者,对自己真正在做什么感到困惑。下面是我到目前为止想到的一个片段。在我尝试处理返回的数据之前,它工作得很好。我认为我的问题是我不太明白如何形成正确的反应以及如何处理它 JAVASCRIPT/JQUERY: var shoppingList = { // SOME CODE BEFORE 'foodIngredients' : function() { // Send a list of

我正在对服务器进行ajax调用,希望接收一个数组以进行进一步处理。我是个初学者,对自己真正在做什么感到困惑。下面是我到目前为止想到的一个片段。在我尝试处理返回的数据之前,它工作得很好。我认为我的问题是我不太明白如何形成正确的反应以及如何处理它

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)
var shoppingList={
//之前的一些代码
“FoodingElements”:函数(){
//发送食物ID列表并接收必要的配料数组。使返回的数组唯一。
$.ajax({
网址:'http://localhost:8000/ingredients/',
//Components.html模板:
//[{%for-items%}{%if-forloop.last%}{{item.id}{%else%}{{{item.id}},{%endif%}{%endfor%}]
键入:“POST”,
数据:JSON.stringify(shoppingList.selectedFoods),
数据类型:“文本”,
缓存:“false”,
成功:功能(结果){
控制台日志(结果);//[33,85,88,89,91]
shoppingList.returnedIngredients=结果;
shoppingList.UniqueComponents=\ uu0.unique(shoppingList.ReturnedIngreents);

console.log(shoppingList.UniqueComponents);//[,3,,,8,5,9,1,]结果是一个字符串,而不是一个数字数组。因此,

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

您能粘贴/components/view的代码吗?@jpic:added components view.@jade:@unique是一个函数Underline.js库中的选项:
result
是一个字符串,而不是一个数字数组。因此
.unique
返回字符串中的唯一字符。您需要使用
jSON.Parse
将结果转换为数组。或者在选项中指定
数据类型:“jSON”
。是的,您是对的。只需指定̣e> 数据类型:“json”
解决了这个问题。我仍然不明白它是如何工作的。json不应该是
key:value
格式吗?json可以用来编码几乎任何类型的JavaScript数据。如果它是一个对象,它就是
{key:value,key:value}
,如果它是一个数组,它就是
[element,element,element]