将变量客户端(JS Ajax)发送到服务器端(Python Django)

时间:2020-02-25 19:16:23

标签: django python-3.x ajax

我正在将Python 3.7.4与Django 3.0.3结合使用,并且在前端应用程序中运行的javascript中有脚本Ajax。当用户单击链接时,必须将变量发送到后端python。参见示例

JavaScript

$('.likebutton').click(function() {
    var catid;
    catid = $(this).attr("data-catid");
    $.ajax({
        type: "GET",
        // url: "/likePost",
        url: "/likePost/" + catid,
        /* data: {
            post_id: catid
        },
        */   
        success: function(data) {
            $('#like' + catid).remove();
            $('#message').text(data);
        }
    })
});

urls.py

在我拥有的应用程序的urlpattner中

urlpatterns = [
    path('', views.index, name='index'),  # index view at /
    path('likePost/', views.likePost, name='likepost'),   # likepost view at /likepost
]

views.py

def likePost(request):
    if request.method == 'GET':
        post_id = request.GET['post_id']
        likedpost = Post.obejcts.get(pk=post_id) #getting the liked posts
        m = Like(post=likedpost) # Creating Like Object
        m.save()  # saving it to store in database
        return HttpResponse("Success!") # Sending an success response
    else:
        return HttpResponse("Request method is not a GET")

在调试中,我收到以下消息错误

Not Found: /likePost
[25/Feb/2020 16:12:17] "GET /likePost?post_id=1 HTTP/1.1" 404 2335

我做错了什么?

1 个答案:

答案 0 :(得分:2)

在ajax脚本中,您正在传递名为 post_id querystring 参数(例如likePost/?post_id=1),但是在urlpatterns中,将 post_id 指定为 path参数(例如likePost/1/)。

您有2个选择:

post_id作为路径参数

post_id 添加到网址中,而不是将其作为数据发送:

$('.likebutton').click(function() {
    var catid;
    catid = $(this).attr("data-catid");
    $.ajax({
        type: "GET",

        // standard syntax
        url: "/likePost/" + catid,

        // template string syntax
        // url: `/likePost/${catid}`,

        success: function(data) {
            $('#like' + catid).remove();
            $('#message').text(data);
        }
    })
});

然后将 post_id 添加到视图:

def likePost(request, post_id):
    ...

post_id作为查询字符串

将路径更改为以下内容:

path('likePost/', views.likePost, name='likepost') 

然后您可以通过视图中的post_id访问 request.GET

def likePost(request):
    post_id = request.GET['post_id']
    ...

此外,如果您不确定要使用哪个选项,建议阅读When do I use path parameters vs. query params in a RESTful API?