首页 > 解决方案 > 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

我不确定我需要在哪里放置请求元素,或者什么不是......

标签: pythonjquerydjangoajaxget

解决方案


推荐阅读