I\'m trying to use ajax in Django to post comment in a news website.However it doesn\'t work.When I click the submit button,it still refreshes the page and make no d
Your binding is incorrect, you have the click handler on the form it should be a submit handler. If you were binding it to a button then you'd use click a handler.
$('#js-pl-submit').on('submit', function(){//<-- here
var comments = $("#js-pl-textarea").val()
if(comments == ""){
alert("评论不能为空")
return false
}
$.ajax({
cache: false,
type: "POST",
url:"",
data:{'news_pk':{{ news.id }}, 'comments':comments},
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data) {
if(data.status == 'fail'){
if(data.msg == '用户未登录'){
window.location.href="login";
}else{
alert(data.msg)
}
}else if(data.status == 'success'){
window.location.reload();//刷新当前页面.
}
},
});
return false;
});