如何解决Python Django Ajax 获取请求在 def 函数
我正在尝试通过 get 方法将一个变量从我的 JQuery Ajax 对象传递到我的 views.py 文件(在 django 中)
我之前使用过一个类,它工作得很好..
views.py 工作代码:
class AjaxHandlerView(View):
def get(self,request):
text = request.GET.get('button_text')
print()
print(text)
print()
if request.is_ajax():
return JsonResponse({'test': 'blah'})
return render(request,'home.html',{'name': 'Handled by AHV'} )
应用 urls.py
from django.urls import path
from . import views
from .views import *
urlpatterns = [
path('',AjaxHandlerView.as_view() ),path('ajaxg',views.ajaxgtest,name="ajaxg" )
]
jquery ajax函数(忽略post方法)
var test_str = "[0,0]";
$(document).ready(function(){
var csrf = $('input[name=csrfmiddlewaretoken]').val()
$('#jq_btn').click(function(){
$.ajax({
url: '',type: 'get',data: {
button_text: test_str
},success: function(response) {
$("#jq_btn").text(response.test + test_str);
console.log(test_str);
}
});
});
$('#post_btn').click(function() {
$.ajax({
url: '',type: 'post',data: {
text: test_str,csrfmiddlewaretoken: csrf
},success: function(reponse) {
test_str = reponse.postdata
console.log(test_str);
}
})
});
});
但是我想对特定方法使用特定函数..所以我尝试使用 def..
views.py 不起作用:
def ajaxgtest(self,request):
text = request.GET.get('button_text')
print(text + "deffer")
if request.is_ajax():
return JsonResponse({'test': 'blah'})
return render(request,{'name': 'Handled by AHV'} )
至于 Jquery 代码,我所做的只是将 url: '' 编辑为 url: 'ajaxg'(我在 urls.py 文件中为视图命名)
新的 jq ajax 代码:
$('#jq_btn').click(function(){
$.ajax({
url: 'ajaxg',success: function(response) {
$("#jq_btn").text(response.test + test_str);
console.log(test_str);
}
});
});
我收到错误代码;
TypeError: ajaxgtest() 缺少 1 个必需的位置参数:'request' [01/Jan/2021 01:25:31]“GET /ajaxg?button_text=%5B0%2C0%5D HTTP/1.1”500 58077
我不确定我需要把请求元素放在哪里,或者什么不......
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。