Reputation: 970
i am using jquery to send json data that contains array of elements like this
$('#brand_category').click(function(event){
category = $("input:checkbox[name=category]:checked").map(function() {
return this.value;
}).get();
brand = $("input[type='radio']:checked").map(function() {
return this.value;
}).get();
parameter.push({
brand : brand,
category: category
});
var json = JSON.stringify(parameter)
$.ajax({
type: 'post',
url: "{% url 'seller_details' %}",
data: {'parameter[]' : json , csrfmiddlewaretoken:'{{csrf_token}}'},
success: function(data){
},
error:function (response, error){
}
});
and in the view i am collecting the data like this
brand_category = self.request.POST.get('parameter[]')
print brand_category
this prints the data as this
[{"brand":["spykar"],"category":["Women Clothing","Dresses"]},{"brand":["Madame"],"category":["Women Clothing","Dresses"]}]
then i tried to loop through the json like this
for list in list_data:
brand = list_data['brand']
print brand
categories = list_data['category']
print categories
but i am getting the error as this
list indices must be integers, not str
how can i loop through the json data to get the list of brands and categories?
Upvotes: 2
Views: 1495
Reputation: 1559
I recommend you this AJAX Request (Its more clear):
$('#brand_category').click( sendAjax );
function sendAjax()
{
var category = $("input:checkbox[name='category']:checked").val();
var brand = $("input[type='radio']:checked").val();
var data = { "category" : category, "brand" : brand, "csrfmiddlewaretoken" : '{{csrf_token}}' }
$.ajax({
type: 'post',
url: "{% url 'seller_details' %}",
data: data,
success: function(data)
{
//console.log(data) // Print the response of Django or see this in "Network" request, F12 Chrome
},
error:function (response, error)
{
}
});
}
View:
category = request.POST['category']
print category
brand = request.POST['brand']
print brand
List data of brands in JavaScript:
var data = {} //This is a empty object named data
data.brans = [];
and then you need create a for select all brands
for ("list of brands"){
brand_name = logic
data.brands.push(brand_name)
} //This is only a idea
Upvotes: 0
Reputation: 3658
Your outer loop is a list, and then you loop through each dictionary in the list. Also, you have to convert the string to a python object.
import json
brand_category = self.request.POST.get('parameter[]')
Lbrand_category = json.loads(brand_category)
for D in Lbrand_category:
brand,categories = D['brand'],D['category']
Note: if you want only the brand string, without the list, use:
brand,categories = D['brand'][0],D['category']
Upvotes: 2