简体   繁体   English

Ajax 电话未接通 Django 查看

[英]Ajax post call not reaching Django view

In my django site i have an API view that is supposed to increment an integer field when called.在我的 django 站点中,我有一个 API 视图,它应该在调用时增加一个 integer 字段。 However, the ajax call says the view is an invalid url. I have tried changing the url multiple times and changing the view.但是,ajax 调用表示视图无效 url。我已尝试多次更改 url 并更改视图。

Here's the error message from console这是来自控制台的错误消息错误信息

Here's my javascript ajax call这是我的 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);

            }
        });
    }

Here's the django view this ajax function is supposed to call这是 django 查看此 ajax function 应该调用

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

And here is my urls.py这是我的 urls.py

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

]

Thanks谢谢

You can simply use /increment/ as AJAX url. This will add /increment/ to your localhost domain.您可以简单地将/increment/用作 AJAX url。这会将/increment/添加到您的本地主机域。

For Absolute path try using对于绝对路径尝试使用

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

or要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM