我正在学习如何在Django中使用Ajax GET和POST,我有这个问题,请你抽出时间来帮助我。谢谢!
我遇到的问题是当我点击POST按钮时,它总是转到views.ajax_get(当我希望它应该转到views.ajax_post时)。
这是HTML模板
<button class="get_button" id="get-button" type="button">Get button</button>
<form method="POST">
{%csrf_token%}
<button class="post_button" id="post-button" type="submit">Post button</button>
</form>
这是Javascripts:
<script>
$(document).ready(function() {
$('.get_button').click(function() {
$.ajax({
type: "GET",
url: "{%url 'myapp:ajax_get' %}",
success: function(response) {
alert('Ajax GET')
}
});
});
$('.post_button').click(function() {
$.ajax({
type: "POST",
url: "{%url 'myapp:ajax_post' %}",
success: function(response) {
alert('Ajax POST');
}
});
});
// CSRF code
function getCookie(name) {
var cookieValue = null;
var i = 0;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (i; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// 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');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
</script>
答案 0 :(得分:1)
您尚未停用表单或按钮的默认操作。因此,Ajax被触发,但随后通过浏览器正常提交表单。