python - 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);
}
})
});
});
但是我想为特定方法使用特定功能..所以我尝试使用定义..
不工作的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,'home.html' , {'name': 'Handled by AHV'} )
至于 Jquery 代码,我所做的只是将 url: '' 编辑为 url: 'ajaxg' (这是我在 urls.py 文件中命名视图的名称)
新的 jq ajax 代码:
$('#jq_btn').click(function(){
$.ajax({
url: 'ajaxg',
type: 'get',
data: {
button_text: test_str
},
success: function(response) {
$("#jq_btn").text(response.test + test_str);
console.log(test_str);
}
});
});
我收到错误代码;
类型错误:ajaxgtest() 缺少 1 个必需的位置参数:'request' [01/Jan/2021 01:25:31] "GET /ajaxg?button_text=%5B0%2C0%5D HTTP/1.1" 500 58077
我不确定我需要在哪里放置请求元素,或者什么不是......
解决方案
推荐阅读
- php - 将 PHP 文件包含到另一个文件中
- google-sheets - 在 BigQuery 中查询 google sheet 连接的永久表时出错
- symfony - 关联字段类型的预期值改为“整数”
- sql - SQL 触发器抛出错误但仍插入
- html - 当我将视频用作正文背景视频时,我的其他内容背景不起作用
- amazon-dynamodb - 如何检查 emaiID 在 dynamodb 中是否存在?
- python - 通过 pandas groupby 计数列的结果过滤
- c# - 如何正确使用 Thread.Abort()?
- java - couchbase 中使用 map reduce 的动态视图
- php - 找不到类“Illuminate\Cache\CacheServiceProvider”