我将此数据传递给POST到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词典一样。
答案 0 :(得分: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']