您可以在模板中使用 JQuery Ajax 并通过在您的 views.py 中创建一个“API 视图”来执行此操作,该视图基本上只是一个常规视图,在检查以验证请求是否为 Ajax 后返回 JSONResponse。作为“API”选项的示例,使用 JQuery:
在您的 views.py 文件中(使用 GET 方法,只有在注释简短时才应使用该方法,它将适合 URL 栏,并且如果您没有重大安全问题,否则请参阅底部的 POST 示例):
from django.http import JsonResponse
def post_note_api(request):
data = {}
if request.GET.get('post_note', None) is not None:
post_note = request.GET.get('post_note')
# save the note and indicate success
data['result'] = True
data['message'] = "Note posted successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
在你的 urls.py 中:
...
path('/api/post_note/', post_note_api, name="post_note_api"),
...
在您的模板中(如果您使用的是 GET 方法):
<script type="text/javascript">
$("#tn1").click(function(){
var message = $("#myTextArea").val();
$.ajax({ url: '{% url 'post_note_api' %}?post_note=' + message,
type: "GET",
dataType: "json",
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
如果您使用的是 POST 方法而不是 GET(这可能是这里更好的选择):
<script type="text/javascript">
$("#tn1").click(function(){
var csrfToken = $( "input[name='csrfmiddlewaretoken']");
var message = $("#myTextArea").val();
$.ajax({ url: '{% url 'post_note_api' %}',
type: "POST",
dataType: "json",
data: {'post_note':message, 'csrfmiddlewaretoken':csrfToken.val()},
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
对于 POST 方法,在您看来,只需将 request.GET.get('post_note') ... 更改为 request.POST.get('post_note') ...,如下所示:
from django.http import JsonResponse
def post_note_api(request):
data = {}
if request.POST.get('post_note', None) is not None:
post_note = request.POST.get('post_note')
# save the note and indicate success
data['result'] = True
data['message'] = "Note saved successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
当您通过 POST 发送数据时,请不要忘记传递您的 CSRF 令牌,如上例所示。这假设您在页面上有一个可以从中获取它的表单,否则您可以使用类似的东西来获取它:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
如果你不想处理 CSRF 令牌,你可以用 @csrf_exempt 装饰器标记视图,并从模板中的 Ajax 调用中删除 'csrfmiddlewaretoken' 数据元素,但它可能不是理想的或最安全的。一个例子:
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
@csrf_exempt()
def post_note_api(request):
...
现在,在不了解更多信息的情况下,这基本上只是伪代码(另外我只是在脑海中写下了这个,所以它可能有错误)。如果您发布更多详细信息,我可以更新我的答案,但我认为这应该让您开始。