반응형
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
반응형
'programing' 카테고리의 다른 글
왜 두 정수를 나누면 부동소수점을 얻을 수 없습니까? (0) | 2023.08.26 |
---|---|
저는 Xampp에 Mifos X를 설치해 보았습니다.브라우저에서 UI에 액세스할 수 있기 때문에 작동했지만 자격 증명에 많은 문제가 있었습니다. (0) | 2023.08.26 |
MariaDB에 대한 InnoDB 전체 텍스트 스톱워드를 올바르게 비활성화하는 방법은 무엇입니까? (0) | 2023.08.26 |
오류 코드: 1062.키 '기본'에 대한 중복된 항목 '1' (0) | 2023.08.26 |
my.cnf(Centos 8)의 mysql에 대한 최적의 설정(mariadb 최적화 10.5) (0) | 2023.08.21 |