简体   繁体   English

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

[英]Sending variable Client Side (JS Ajax) to Server Side (Python Django)

I am using Python 3.7.4 with Django 3.0.3 and I have a script Ajax in javascript run in the front end app.我正在将 Python 3.7.4 与 Django 3.0.3 一起使用,并且我在前端应用程序中运行的 javascript 中有一个脚本 Ajax。 When the user click in link, a variable must to be sending to back end python.当用户单击链接时,必须将变量发送到后端 python。 See the exemple看例子

Javascript 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网址.py

In the urlpattner of app I have在应用程序的 urlpattner 中,我有

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

views.py视图.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")

In Debug I received the follow message error在调试中,我收到以下消息错误

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

What I am doing wrong?我做错了什么?

In your ajax script, you are passing a querystring parameter called post_id (eg. likePost/?post_id=1 ), but in your urlpatterns, you specify post_id as a path parameter (eg. likePost/1/ ).在您的 ajax 脚本中,您传递了一个名为post_id查询字符串参数(例如, likePost/?post_id=1 ),但在您的 urlpatterns 中,您将post_id指定为路径参数(例如, likePost/1/ )。

You have 2 options:您有 2 个选择:

post_id as a path parameter post_id 作为路径参数

Add the post_id to the url instead of sending it as data:post_id添加到 url 而不是将其作为数据发送:

$('.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);
        }
    })
});

Then add post_id to your view:然后将post_id添加到您的视图中:

def likePost(request, post_id):
    ...

post_id as a querystring post_id 作为查询字符串

change your path to the following:将您的路径更改为以下内容:

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

You can then access post_id via request.GET in your view:然后,您可以在您的视图中通过request.GET访问post_id

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

Furthermore, I'd recommend reading When do I use path parameters vs. query params in a RESTful API?此外,我建议阅读何时在 RESTful API 中使用路径参数与查询参数? if you aren't sure of which option to use.如果您不确定要使用哪个选项。

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

相关问题 将客户端数据发送到服务器端的问题(django) - Problem with sending client side data to server side (django) 浏览Django / Python中的客户端和服务器端文件? - Browse client side and server side files in Django/Python? 解析Django模型服务器端还是客户端? - Parse Django Models Server Side or Client Side? 通过变量将序列化的数据从js发送到服务器端 - Sending a serialized data from js to server side in a variable Django服务器端AJAX验证 - Django server side AJAX validation 反转 'my_views_name' 没有找到任何参数。 django - jquery ,将服务器端与客户端 js 连接起来 - Reverse for 'my_views_name' with no arguments not found. django - jquery , connect server side with client side js Django模板-服务器端django标签的客户端操作 - Django Templates - client side manipulation of server side django tag 从服务器端Python将JSON对象获取到客户端Django模板中 - Get JSON object from server-side Python into client-side Django template Facebook身份验证:服务器端与客户端。 的Python / Django的 - Facebook authentication: server-side versus client-side. Python/Django 在服务器端 Django REST 中使用 API 并在 ZC31C318BA0372813DE1Z51 中为客户端提供服务 - Consume an API in Django REST, server side, and serve it ,client side, in Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM