【问题标题】:Ajax post call not reaching Django viewAjax post call 未到达 Django 视图
【发布时间】:2020-09-01 23:22:18
【问题描述】:

在我的 django 站点中,我有一个 API 视图,它应该在调用时增加一个整数字段。但是,ajax 调用说视图是无效的 url。我曾尝试多次更改网址并更改视图。

这是来自控制台的错误消息

这是我的 javascript ajax 调用

    function post_(amount){
        return $.ajax({
            url: '127.0.0.1:8000/increment/',
            type: "POST",
            data: {
                "amount": amount,
                "user": "{{ user.username }}",
            },
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (error) {
                console.log("Error Message: ");
                console.log(error);

            }
        });
    }

这是这个 ajax 函数应该调用的 django 视图

@api_view(['POST'])
def Increment(request):
    amount = request.data['amount']
    #username_m = request.data['user']
    #profile = Profile.objects.filter(user=username_m)
    profile = get_object_or_404(Profile, user=request.user)
    print(profile)
    profile.coins += amount
    profile.save(update_fields=['coins'])
    return Response({"message": "Got some data!", "data": request.data})

这是我的 urls.py

urlpatterns = [
    path('increment/', views.Increment, name='increment'),

]

谢谢

【问题讨论】:

  • 将 url: '127.0.0.1:8000/increment/' 改为 url: '/increment/',并返回 JsonResponse insted of Response

标签: javascript python django ajax django-views


【解决方案1】:

您可以简单地使用 /increment/ 作为 AJAX 网址。这会将/increment/ 添加到您的本地主机域。

【讨论】:

    【解决方案2】:

    对于绝对路径尝试使用

    url: 'http://localhost:8000/increment/' 
    

    url: 'http://127.0.0.1:8000/increment/'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2019-04-06
      • 2012-04-15
      • 2013-06-03
      • 2017-11-16
      • 2015-02-03
      相关资源
      最近更新 更多