【问题标题】:Why does my AJAX post request not work correctly?为什么我的 AJAX 发布请求无法正常工作?
【发布时间】:2015-01-16 01:22:42
【问题描述】:

我在 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 请求”以确认该方法是否被调用,但是当我测试这个时,终端没有打印,我不知道为什么。

【问题讨论】:

  • 如果 AJAX 试图显示警报,为什么要在视图中进行重定向?在用户名值中使用引号使 JavaScript 检测值而不是变量。
  • 哦,好的,我要删除警报。我想要的只是重定向。
  • 如果你只想要重定向,你应该返回一个带有你想要重定向到的 URL 的 HttpResponse,并在 AJAX 成功调用中进行重定向
  • 为什么我不能在视图中完成所有这些操作?

标签: jquery ajax django


【解决方案1】:

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

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

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

【讨论】:

  • 你认为这也是为什么我的视图方法中“检测到 ajax 请求”没有打印的原因吗?
猜你喜欢
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
相关资源
最近更新 更多