为什么我的AJAX帖子请求无法正常工作?

时间:2015-01-15 17:21:50

标签: jquery ajax django

我在Django中的AJAX方法似乎没有工作,我无法确定它被破坏的地方,因为我实际上没有在Django调试日志中收到任何错误,它返回了200状态代码。

模板

<script type="text/javascript">
    var my_app = {
      username: {{ request.user.username }}  
    };
</script>
<script>
 $(document).ready(function() {
    $(".delete_button").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            type: "POST",
            url: "/accounts/" + my_app.username + "/profile_listview",
            data: { entryname:id },
            success: function(response){
                alert(response.success);
            }
        });
        return false;
    });
});
</script>

或者错误可能在实际的jQuery AJAX部分? Chrome开发者控制台给出了以下错误:

Uncaught ReferenceError: benjamin is not defined(index):223 (anonymous function)

我不知道究竟是什么意思,但事实上它说的是benjamin,意味着这个名称已被正确分配。

VIEWS.PY

latest_entries=Entry.objects.order_by('-pub_date')[:16]

@login_required
def delete_object(request):
   if request.is_ajax():
      print "ajax request detected"
      object_name = request.POST.get('entryname')
      Entry.objects.get(id=object_name).delete()
      return HttpResponseRedirect('/storefront/')

我应该提到的另一件事是我添加了打印“检测到ajax请求”以确认该方法是否被调用,但在我测试时没有任何内容打印到终端,我不知道为什么。

1 个答案:

答案 0 :(得分:2)

您需要将用户名放在引号中:

var my_app = {
    username: '{{ request.user.username }}'
};

Benjamin is not defined错误是因为JavaScript认为您引用了该名称的变量,而不是定义字符串值。

相关问题