我是Django的新手,试图开发一个聊天网络项目,但被卡住了。有人能告诉我应该使用哪种方法吗?我想在不更改URL的情况下将textbox数据传递给Python,但我无法传递它。我的Javascript代码
$("#button").click(function(){
var msg = $('#textbox').val();
$("<div class='user' id='user'>"+msg+"</div>").insertBefore('.insert_after');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);我在下面使用了这段ajax代码。但是,我无法在views.py文件中检索结果
$('.ajaxProgress').show();
$.ajax({
type: "POST",
url: "http://localhost:8080/bot/",
dataType: "json",
async: true,
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
message: $('#textbox').val()
},
success: function(json){
$('#test').html(json.message);
$('.ajaxProgress').hide();
}
});
$('#textbox').val("");
});有人能解释一下如何在views.py中使用它吗?我得到了一个csrf_token的禁止错误,
发布于 2018-07-29 13:52:19
在您的js代码中有一个小错误。
$(document).ready(function() {
$("#button").click(function(){
//some code
var msg = $('#textbox').val();
$('#textbox').val(""); /*if you are assigning "" to textbox */
$.ajax({
type: "POST",
url: "/bot/",
dataType: "json",
async: true,
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
message: msg /*then here you have to use msg*/
},
success: function(json){
//further code
}
});
$('#textbox').val("");
});
});而说到csrf_token的禁止错误,你必须参考this来解决
参考工作代码here
发布于 2018-07-29 16:25:42
是的,很多人都会收到这样的错误,放在html的末尾。如果你有一个base.py,你所有的模板都是从它扩展而来的,你也可以把它放进去。这解决了AJAX csrf_token问题。这可能是一个重复的答案,但我找不到我的另一个帖子与此代码。
{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>编辑:找到了我的另一篇文章。
https://stackoverflow.com/questions/51577363
复制相似问题