首页 > 解决方案 > 无法在 Django 视图函数中检索 AJAX 请求数据值

问题描述

我有一个 AJAX 请求从 post 模型中提取一些数据“我正在使用 Django3 和 python 3.8”。当我将 request.GET.get 打印到控制台时,我得到“无”。没有数据。但是,当我在 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)

print 函数打印这一行。

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 时。我有所有帖子详细信息的对象。
非常感谢您的建议和指导。

标签: jquerydjangoajax

解决方案


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);
        }
    }
});

推荐阅读