0

I have this data passed in a POST to django view:

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},
     });

The data looks like this:

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

Now in the view i want to loop over passed data, access it and then do something with it in 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)

I don't know how to access single values and keys, just like it would be python dictionary.

1 Answer 1

1

While this is very old I found myself searching for this exact problem...

I found a way that works although I feel it is a bit unreliable

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.