2012-10-30 126 views
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 
}; 

Ingredients查看:

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) 
+0

你可以粘貼/成分/視圖的代碼? – jpic

+0

郵政編碼爲_.unique – iJade

+0

@jpic:添加配料視圖。 – finspin

回答

1

結果是一個字符串,而不是數字的陣列。所以_.unique正在返回字符串中的唯一字符。您需要使用jSON.Parse將結果轉換爲數組。或在選項中指定dataType: 'json'

+0

是的,你是對的。只需指定̣̣'dataType:'json''即可解決問題。我仍然不明白它是如何起作用的。 json是不是應該是'key:value'格式? – finspin

+1

JSON可用於編碼幾乎任何類型的JavaScript數據。 ifit是一個對象,它是'{key:value,key:value}',如果它是一個數組,它就是'[element,element,element]'。 – Barmar