programing

jQuery ajax 호출을 통해 django 뷰에 값 목록 전달

minimums 2023. 8. 26. 10:39
반응형

jQuery ajax 호출을 통해 django 뷰에 값 목록 전달

jQuery ajax 호출을 통해 한 웹 페이지에서 다른 웹 페이지로 숫자 값(id) 목록을 전달하려고 합니다.목록에 있는 모든 값을 어떻게 전달하고 읽는지 알 수 없습니다.1개의 값을 성공적으로 게시하고 읽을 수 있지만 여러 개의 값은 읽을 수 없습니다.지금까지 제가 가진 것은 다음과 같습니다.

jQuery:

var postUrl = "http://localhost:8000/ingredients/";
$('li').click(function(){
    values = [1, 2];
    $.ajax({
        url: postUrl,
        type: 'POST',
        data: {'terid': values},
        traditional: true,
        dataType: 'html',
        success: function(result){
            $('#ingredients').append(result);
            }
    });       
});

/성분/ 보기:

def ingredients(request):
    if request.is_ajax():
        ourid = request.POST.get('terid', False)
        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)

Firebug를 사용하면 POST에 두 ID가 모두 포함되어 있지만 형식(terid=1&terid=2)이 잘못되었을 수 있습니다.그래서 내 재료 보기는 terid=2만 선택합니다.내가 뭘 잘못하고 있는 거지?

EDIT: 명확하게 하기 위해 성분 보기의 필터에 id 변수 값 [1, 2]을 전달해야 합니다.

요청을 통해 이 어레이에 액세스할 수 있습니다.보기의 POST.getlist('terid[]')

Javascript로:

$.post(postUrl, {terid: values}, function(response){
    alert(response);
});

시야에py:

request.POST.getlist('terid[]')

저한테 딱 맞습니다.

저는 제 원래 문제에 대한 해결책을 찾았습니다.누군가에게 도움이 되기를 바랍니다.

jQuery:

var postUrl = "http://localhost:8000/ingredients/";
$('li').click(function(){
    values = [1, 2];
    var jsonText = JSON.stringify(values);
    $.ajax({
        url: postUrl,
        type: 'POST',
        data: jsonText,
        traditional: true,
        dataType: 'html',
        success: function(result){
            $('#ingredients').append(result);
            }
    });       
});

/성분/ 보기:

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)

이 부분이 문제입니다.

ourid = request.POST.get('terid', False)
ingredients = Ingredience.objects.filter(food__id__in=ourid)

JSON 문자열을 역직렬화해야 합니다.

import json
ourid = json.loads(request.POST.get('terid'))

여기서 배열을 문자열로 설정하는 것 같습니다.

data: {'terid': values},

그럴 것 같네요.

data: {terid: values}

다음과 같은 데이터 전송 시도:

   data: values;

언급URL : https://stackoverflow.com/questions/11176594/passing-list-of-values-to-django-view-via-jquery-ajax-call

반응형