我正在创建一个网页,用户提交一个表单,然后在Django中创建一个对象(使用Ajax,因此页面不刷新)。当我在成功的响应部分中不包含.append()方法时,此工作正常。Ajax/Django .append()发送POST请求
但是,当我试图在成功请求后添加一个新的语义UI卡时,页面通过普通的POST请求刷新并提交给Django,而不是通过Ajax,因此页面不刷新。你知道这可能是为什么吗?
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!")
create_post();
});
function create_post() {
$.ajax({
url : "/create_post/", // the endpoint
type : "POST", // http method
data : { post : $('#post').val() }, // data sent with the post request
// handle a successful response
success : function(json) {
$('#post').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
// this causes the page to refresh and the form to POST
$('#add-card').append("
<div class='ui card'>
<div class='content'>
<div class='description'>
Test Test test
</div>
</div>
</div>
");
console.log("success");
},
});
};
和HTML页面:
<div class="ui four cards" id="add-card">
<div id="add-card">
</div>
</div>
谢谢,这个作品!为了将来的参考,JavaScript错误应该打印到控制台?我没有得到任何错误,并想知道如何捕捉错误? –
是的,他们应该是,但如果页面在同一时间重新加载,您将失去控制台中的内容,因此在这种情况下您可能会忽略它。当然,你总是可以把东西包装在旧的'try {...} catch(ex){...}' – csum
此外,控制台体验将取决于你的浏览器。 (有些浏览器没有定义'console'对象,因此如果代码要进入生产环境,请注意'console.log()'调用。) – csum