2013-08-26 61 views
0

我已經在POST通過此數據來Django的觀點:如何訪問多個JSON對象的數組發送的Django

var jobj = []; 

$('.some_class').each(function(){ 
       var ro = $('#some_id').html(); //html() output is number 
       var nr = $('#something').html(); //html() output is number 
       var item = {}; 
        item["prog"] = ro; 
        item["act"] = nr;      
        jobj.push(item); 
       }); 
      arr = JSON.stringify(jobj); 

    ajax_req = $.ajax({ 
    url: '../some_url/', 
    type: "POST", 
    data: {req_arr : arr}, 
    }); 

的數據是這樣的:

req_arr = [{"prog" : "1", "act" : "0"}, {"prog" : "2", "act" : "0"}, (...)] 

現在在視圖中我要循環傳遞的數據,訪問它,然後用它做什麼在SQL:

def some_url(request): 

if request.method == 'POST': 
    arr = request.POST['req_arr'] 
    for data in arr: 
     prog = data['prog'] 
     act = data['act'] 
     (...) some sql stuff like SomeModel.objects.get(name=prog) (...) 

    return HttpResponse(status=200) 

我不知道如何訪問單個值和鍵,強制不喜歡它會是python字典。

回答

1

雖然這是很老了,我發現自己尋找這個確切的問題...

我發現,工作雖然我覺得這是一個有點靠不住

的Javascript的方式:

var rows = []; 
$('.some_class').each(function(){ 
    var id = $(this).attr('data-id'); 
    var something = $(this).attr('data-something'); 
    var item = {}; 

    item["id"] = id; 
    item["something"] = something;      
    rows.push(JSON.stringify(item)); 
}); 

arr = rows.join("/"); 

ajax_req = $.ajax({ 
    url: '../some_url/', 
    type: "POST", 
    data: {req_arr : arr}, 
}); 

views.py

items = request.POST.get('req_arr', None) 
items = str(items).split("/") 

for i in range(0, len(items)): 
    item = json.loads(items[i]) 
    id = item['id'] 
    something = item['something']