我试图将Ajax用于Django网站中的简单部分。单击时的类似按钮喜欢该帖子,但HTML并未更改。如果我刷新页面,则HTML会更改。
控制台显示以下错误
未介绍的参考文献:未定义响应 在object.success((索引):271) 在u(jquery.min.js:2) 在object.firewith [as asolveWith](jquery.min.js:2) 在K(jquery.min.js:2) 在xmlhttprequest。(jquery.min.js:2)
JavaScript在下面给出
<script type="text/javascript">
$(document).ready(function(event){
$(document).on('click','#like', function(event){
event.preventDefault();
var pk= $(this).attr('value');
$.ajax({
type:'POST',
url:'{% url "like_post" post.id %}',
data:{'blog_id':pk,'csrfmiddlewaretoken':'{{ csrf_token}}'},
dataType:'json',
success: function(event){
$('#like-section').html(response['form'])
},
fail:function(rs, e){
console.log(rs, responseText);
},
});
});
});
</script>
html
<div>
<form action="{% url 'like_post' post.id %}">
{% csrf_token %}
{% if is_liked %}
<button id="like" type='submit' name='blog_id' value="{{ post.id }}" class="btn ">unlike</button>
{% else %}
<button id="like" type='submit' name='blog_id' value="{{ post.id }}" class="btn ">like</button>
{% endif %}
</form>
</div>
以下是HTML页面的代码
<div id="like-section">
{% include 'blog/like_section.html' %}
</div>
未定义您的变量'响应'。您的AJAX成功处理程序具有"事件",将事件更改为"响应",并且应该起作用。
success: function(response){
$('#like-section').html(response['form'])
},
您正在遇到此错误,因为您的成功方法不知道什么是响应。尝试通过响应而不是事件,检查事件[响应] ['form'],或记录事件对象以查找所需的内容。