Ajax not work in Django post

前端 未结 4 542
温柔的废话
温柔的废话 2021-01-17 01:53

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

4条回答
  •  遇见更好的自我
    2021-01-17 02:34

    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;
    });
    

提交回复
热议问题