繁体   English   中英

如何在 Django 中检索信息 - 发布请求?

[英]How to retrieve information in Django - Post Request?

我正在尝试通过 ajax 向 Django 发送一个 JavaScript 数组,如下所示:

document.getElementById('input-generate').onclick = () => {

    // Get the token
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    // Create new request add token 
    const generateRequest = new XMLHttpRequest();
    generateRequest.open('POST', '/generate');
    generateRequest.setRequestHeader('X-CSRFToken', csrftoken);

    generateRequest.onload = () => {

        console.log('generateRequest');

    };

    // Add the motif to send with the request
    const data = new FormData();
    console.log(notes);
    // [{…}] 0: {duration: "4", note: "E4", dot: false} length: 1 __proto__: Array(0)
    data.append('motif', notes);

    // Send request
    generateRequest.send(data);
};

在 views.py 上:

@require_http_methods(["POST"])
def generate(request):

    # See if method was post
    if request.method == "POST":

        # Retrive seed
        seed = request.POST.get("motif")
        print(seed)
        print(type(seed))

        # Sanity check
        if not seed:
            return JsonResponse({"succes": False}, status=400)

        # Return the seed
        return JsonResponse({"seed": seed}, status=200)

但是当我打印种子并输入(种子)时,我只看到:

[object Object]
<class 'str'>

如何打印我发送的实际数组?

顺便说一句:我正在尝试发送和编码音符的字符串数组,例如:

notes = [{duration: "4", note: "E4", dot: false}, {duration: "8", note: "D4", dot: false}, {duration: "2", note: "F4 ",点:假}]

我相信您需要在您的notes数组上调用JSON.stringify才能正确发送。 特别是因为您的内容类型将是表单数据。 然后 Django 应该在您的视图中解析传入的 JSON。

对 JavaScript 的示例更改:

document.getElementById('input-generate').onclick = () => {

    let notes = [{duration: "4", note: "E4", dot: false}]  // sample data

    // Get the token
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    // Create new request add token 
    const generateRequest = new XMLHttpRequest();
    generateRequest.open('POST', 'http://127.0.0.1:8000/watchdesk');
    generateRequest.setRequestHeader('X-CSRFToken', csrftoken);

    // Add the motif to send with the request
    const data = new FormData();
    console.log(notes);
    data.append('motif', JSON.stringify(notes));  // stringify notes

    // Send request
    generateRequest.send(data);
};

我只是在没有对视图进行任何更改的情况下对此进行了测试,它似乎有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM