我是Django的新手,他尝试开发一个聊天Web项目并陷入困境。有人可以帮助我使用哪种方法吗? 我想在不更改URL的情况下将文本框数据传递给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的禁止错误,
答案 0 :(得分:0)
您的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
答案 1 :(得分:0)
是的,很多人都会收到此类错误,请放在html的末尾。如果您有一个 <?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_10">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-all:1.9.5" level="project" />
</component>
</module>
,所有模板都从那里扩展,则也可以将其放在其中。这解决了AJAX csrf_token问题。这可能是重复的答案,但是我找不到使用此代码的其他帖子。
base.py
编辑:找到了我的另一篇文章。