发送json对象到Django框架返回500代码错误

djp7away  于 2023-02-17  发布在  Go
关注(0)|答案(1)|浏览(214)

我用 AJAX 发送一个对象到Django视图。我发送的数据是鼠标移动,每10秒发送到服务器保存。现在,我从客户端和服务器端阅读数据没有问题。数据保存在数据库中。但是每次发送到服务器的函数执行时,我都会收到500错误消息。我尝试使用fetch,但收到以下错误消息:

POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

我搜索了此错误,我的理解是此问题与数据类型有关,但我不确定如何跟踪并修复此问题。有人能帮助我解决此问题吗?
下面是我js函数:

var target_id = '';
var eventsLog = {"mouse": []};

  function logMouse(event){
  target_id = event.target.id;
  currDate = new Date()
  start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds();

 var insert = [start_time, target_id];
  (eventsLog.mouse).push(insert);
}
var timesPerSecond = 5; 
var wait = false;
$(document).on('mousemove', function (event) {
  if (!wait) {   
      logMouse(event);
      wait = true;
      setTimeout(function () {
          wait = false;
      }, 1000 / timesPerSecond);
  } 
});
const post_url = server_url;
  function sendMovement() {
   /* fetch(post_url, {
      method: 'POST',
      body: JSON.stringify(eventsLog),
      credentials: 'include',
      headers: {'Content-Type': 'application/json'}
  }).then(res => res.json()).then(response => {
      console.log('POST response:', response);

  }).catch(error => {
      console.log('POST error:', error);
  });*/

    $.ajax({

type: "POST",
url: server_url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(eventsLog),
dataType: "json",

success: function () {
  
      },
      error: function (req, textStatus, errorThrown){
        console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown)
      }
});

这是我的Django观点:

movement = json.loads(request.body.decode('utf-8'))

我检查了Django接收到的数据类型,它是一个字典。

vc9ivgsu

vc9ivgsu1#

从cookie中检索csrftoken并将其附加到请求头中。使用setInterval()每十秒发送一次请求。当然,您可以使用Fetch API来实现,但由于您在移动函数中使用了jQuery,因此我也使用它来发送 AJAX 。
get_mouse_movement.html(仅脚本部分)

<script>
    var target_id = '';
    var eventsLog = {"mouse": []};
    var timesPerSecond = 5; 
    var wait = false;

    function getCookie(name) {
        ...
    }

    function logMouse(event){
        target_id = event.target.id;
        currDate = new Date()
        start_time = currDate.getHours() + ':'
            + currDate.getMinutes() + ':' 
            + currDate.getSeconds() + ':' 
            + currDate.getMilliseconds();

        console.log([start_time, target_id])
        eventsLog.mouse.push([start_time, target_id]);
    };

    $(document).on('mousemove', function (event) {
        if (!wait) {   
            logMouse(event);
            wait = true;
            setTimeout(function () {
                wait = false;
            }, 1000 / timesPerSecond);
        }
    });

    function sendLog() {
        $.ajax({
            type: "POST",
            url: '/your/url/',
            headers: {'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'application/json'},
            data: JSON.stringify(eventsLog),
            success: function(data) {
                console.log(data.message);
                eventsLog.mouse = [];
            },
        });
    };

    setInterval(function(){
        sendLog();
    }, 10000);
</script>

views.py

import json
from django.http import JsonResponse

def mouse_movement(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print(data)
        return JsonResponse({'message': 'log is saved'})
    return render(request, 'get_mouse_movement.html')

.loads()接受、str、bytes或bytearray,不需要解码。

相关问题