2023. 4. 9. 11:03ㆍdjango
다음은 Django와 Ajax를 사용하여 데이터를 가져와서 JSON으로 처리하는 샘플 코드입니다.
urls.py에 URL 패턴 추가하기
from django.urls import path
from . import views
urlpatterns = [
path('get-data/', views.get_data, name='get_data'),
]
views.py에 get_data 함수 추가하기
from django.http import JsonResponse
def get_data(request):
# if request.is_ajax():
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
data = {
'message': 'Hello, World!'
}
return JsonResponse(data)
템플릿에 Ajax 코드 추가하기
<!DOCTYPE html>
<html>
<head>
<title>Django Ajax Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#get-data-button').click(function() {
$.ajax({
url: '/get-data/',
dataType: 'json',
success: function(data) {
$('#result').html(data.message);
}
});
});
});
</script>
</head>
<body>
<h1>Django Ajax Example</h1>
<button id="get-data-button">Get Data</button>
<div id="result"></div>
</body>
</html>
서버 실행 후 페이지 열기
python manage.py runserver
브라우저에서 http://localhost:8000/ 주소를 열고 "Get Data" 버튼을 클릭하면 "Hello, World!" 메시지가 나타납니다. 이 코드는 Ajax를 사용하여 get_data() 함수에서 반환된 데이터를 JSON 형식으로 처리하고, success 콜백 함수에서 메시지를 HTML 페이지에 표시합니다.
'django' 카테고리의 다른 글
input에서 전화번호에 '-' 표 (0) | 2023.04.16 |
---|---|
html select choices 적용 (0) | 2023.04.16 |
django 에서 urls에 적용된 이름을 html로 직접 입력하면 실행이 되나요 (0) | 2023.04.09 |
django에서 데이터베이스의 특정 테이블에서 models 를 자동 작성 (0) | 2023.04.09 |
모델에서 choices 사용시 출력방법 (0) | 2023.04.06 |