ajax
<script>
const funcName = function () {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: 'post요청을 받을 url주소',
headers: {
'X-CSRFTOKEN': '{{ csrf_token }}'
},
data: JSON.stringify(post방식으로 전송할 데이터),
success: (res) => {
resolve(res);
},
error: (e) => {
reject(e);
}
});
});
}
$(document).on('click', "#btn", async () => {
try {
const res = await funcName();
console.log(res);
} catch (e) {
console.log(e);
}
});
</script>
view
받은 데이터를 그대로 다시 return하는 경우
data = json.loads(request.body)
return JsonResponse(data)
특정 데이터를 queryset을 사용하여 조회후 return하는 경우
data = Data.objects.all()
data = list(data.values())
return JsonResponse(data, safe=False)
출처
[JS] jQuery ajax와 async / await
Ajax (Callback, Promise, async/await)
Django에서 '딱 하나'의 DB query를 JsonResponse으로 회신
'BACK-END > Django' 카테고리의 다른 글
[Django] AttributeError: 'function' object has no attribute 'as_view' (0) | 2021.10.08 |
---|---|
[Django] admin에서 저장한 시각과 db에 저장된 시간이 다를 때 (0) | 2021.10.08 |
[Django] django.core.exceptions.ImproperlyConfigured (0) | 2021.10.06 |
[Django] Template에서 Dictionary 접근 (0) | 2021.07.29 |