在Django视图函数中无法检索AJAX请求数据值。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Django视图函数中无法检索AJAX请求数据值。相关的知识,希望对你有一定的参考价值。

我有一个AJAX请求,从post model中提取一些数据 "我使用Django3和python 3.8"。当我打印request.GET.get到控制台时,我得到了 "None"。没有数据。然而,当我在javascript中提醒传递的数据时,我得到了正确的值。我不知道我的代码中的哪一部分应该调整一下才行。

下面是AJAX调用。

   <script type="text/javascript">
   // to submit the get request and prevent the default submission
  $(document).on('click', '#post-det', function(e) 
    e.preventDefault();


    var post_id = $(this).children(':first-child').text();
    var post_id = parseInt(post_id);
    alert(post_id);

    $.ajax(
        'type':'GET',
        'url': "% url 'get_post_details' %",
        'data':post_id,
        'processData': false,
        'cache':false,
        'contentType': false,
        'dataType': 'json',
        csrfmiddlewaretoken:' csrf_token ',

        success: function(data) 

          alert(data)
        ,

    );
    );  
   </script>

我得到了post_ID的 "2"

但是,我无法在Django视图函数中检索到它。下面是视图函数。

def post_details(request):
if request.method == 'GET' and request.is_ajax:


    post_id = request.GET.get('data')
    print("this is to check if the post_id is passed", post_id)
    print(request.GET.get)

    data = GetPostDetails(post_id)
    data = json.dumps(str(data))
    return JsonResponse(data, safe=False)
return JsonResponse("error": "there was an error", status=status.HTTP_400_BAD_REQUEST)

打印函数打印这一行。

this is to check if the post_id is passed None

<bound method MultiValueDict.get of <QueryDict: '_': ['2345678976543']>>
[04/May/2020 08:22:21] "GET /post/Post_details/?_=2345678976543 HTTP/1.1" 200 8

另外,这是请求头。

Request URL: // I removed it 
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
Response Headersview source
Content-Length: 8
Content-Type: application/json
Date: Mon, 04 May 2020 08:06:50 GMT
Server: WSGIServer/0.2 CPython/3.8.2
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Request Headersview source
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Cookie: //I removed it//
Host: 127.0.0.1:8000
Referer: http://127.0.0.1:8000/ // I removed it 
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: // I removed it 
X-Requested-With: XMLHttpRequest

注意:我没有任何错误信息,但json返回空对象,当我硬编码的post_id,并使其post_it = 1 。我有对象与所有帖子的详细信息。你的建议和指导是非常感激的。

答案
Try this as Igor Moraru suggest, using post:


# Python

def post_details(request):
    if request.method == 'POST' and request.is_ajax:

        post_id = request.POST.get('post_id')

        data = GetPostDetails(post_id)
        data = json.dumps(str(data))
        return JsonResponse(data, safe=False)




// Java script


$(document).on('click', '#post-det', function(e) 

    e.preventDefault();

    var post_id = $(this).children(':first-child').text();
    var post_id = parseInt(post_id);

    $.ajax(
          type: "POST",
          url: "% url 'get_post_details' %",
          dataType: "json",
          data: 
              "post_id": post_id
          ,
          success: function(data) 
             console.log(data);
          
      );

);

// Send the csrftoken
function getCookie(name) 
    var cookieValue = null;
    if (document.cookie && document.cookie != '') 
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) 
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) 
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            
        
    
    return cookieValue;


var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) 
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));


$.ajaxSetup(
    beforeSend: function(xhr, settings) 
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) 
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        
    
);
另一答案

正如你所看到的,在你的请求中,没有数据传递给api。你可能想使用POST请求来发送数据。GET方法不接受数据参数。

以上是关于在Django视图函数中无法检索AJAX请求数据值。的主要内容,如果未能解决你的问题,请参考以下文章

无法在 django 视图中从 POST 检索数据

无法在 aws amazon linux v2 内的 django 视图函数中检索或创建数据库对象

无法将 ajax json 发布请求发送到 django 视图

ajax请求返回django.urls.exceptions.NoReverseMatch后Django反向和重定向

56. Django 2.1.7 处理ajax请求GETPOST请求

ajax实现用户注册