首页 > 解决方案 > 从 Javascript 发送到 Django Views 的 JSON 对象为空

问题描述

我正在尝试通过 ajax 将一些数据从 Javascript 发送到 Django。这是我的 JS 代码:

            var json_name = {'name': 123}
            $.ajax({
            method: 'POST',
            url: 'my url',
            contentType: "application/json",
            headers: {
                    'Content-Type':'application/json',
                    'X-CSRFToken': "{{ csrf_token }}"
                },

            data: JSON.stringify(json_name),
            success: function (data) {
         //this gets called when server returns an OK response
            alert("it worked!");
            },
        error: function (data) {
             alert("it didnt work");
            }
        });

这是我的 Views.py:

def myview(request):
    if request.is_ajax():
       request_data = request.body
       # data = json.loads(request.body)
       print(request_data)
       # print(data)
       return render(request, 'candidate/view.html')
    else:
       return render(request, 'candidate/view.html')

我得到的输出为b''

当我尝试包含这些行时:

data = json.loads(request.body)
print(data)

我收到此错误:

TypeError: the JSON object must be str, not 'bytes'

我从这里拿了一些参考

有人可以帮我弄这个吗?如果您需要任何其他信息来解决此问题,我很乐意分享。

标签: javascriptjsonajaxdjango

解决方案


在我的头上掉了一半头发后,我通过以下方式解决了它:

视图.py:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def myview(request):
if request.is_ajax():
    if request.method == 'POST':
        data = request.POST.get('senddata')
        print(data)
    return render(request, 'candidate/view.html')
else:
    return render(request, 'candidate/view.html')

我的 JS 代码:

            <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

            $.ajax({
            type: 'POST',
            url: 'my url',
            // contentType: "application/json",
            // headers: {
      //               'Content-Type':'application/json',
      //               'X-CSRFToken': "{{ csrf_token }}"
      //           },
            dataType: "json",
            data: {
                senddata: JSON.stringify(json_name),
                },

            // data: json_name,

            success: function (data) {
         //this gets called when server returns an OK response
            alert("it worked!");
            },
        error: function (data) {
             alert("it didnt work");
            }
        });

当我运行它时,它会显示,it didnt work但我可以在终端中看到输出,即数据已通过。

我尝试在 ajax 请求中包含 csrf 令牌,但失败了。因此,我在视图中使用了 csrf_exempt。

这可能是一种肮脏的做事方式,但它现在有效。如果有人有一个整洁和更好的答案,请在此处发布!


推荐阅读