[英]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 个选择:
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):
...
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.