0

サーバーに対して 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)
4

1 に答える 1

1

結果は数値の配列ではなく文字列です。したがって、 _.unique は文字列内の一意の文字を返しています。jSON.Parse結果を配列に変換するには、を使用する必要があります。またはdataType: 'json'オプションで指定してください。

于 2012-10-30T09:18:41.053 に答える