如何从XHR获取解析后的请求数据

2024-09-28 05:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码从javascript向Flask服务器发送POST请求:

var form = document.getElementById('addbug');
fd = new FormData(form);

function senddata() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log("Response Received");
        }
    }
    xhr.open('POST', '/addbug');
    xhr.setRequestHeader('Content-type','binary/octet-stream');
    xhr.setRequestHeader('Content-transfer-encoding','binary');
    xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
    fd.append('bug_summary',document.getElementById('bug_summary').value);
    fd.append('csrf_token',document.getElementById('csrf_token').value);
    xhr.send(fd);
    return false;
}

当我在python脚本中读取这些数据时,我面临两个问题:

  1. 变量请求.窗体['addbug']未填充-即为空。以下命令:

    ^{pr2}$

    退货 不可变multidict([])

  2. 我只能使用request.get_数据函数确实有数据,但格式如下:

    ------WebKitFormBoundaryG4ehfDXtXEwIsktm
    Content-Disposition: form-data; name="bug_summary"
    
    test bug
    ------WebKitFormBoundaryG4ehfDXtXEwIsktm
    

如何以最干净的方式从请求主体获取数据?最好的选择是使用请求.窗体条目,但似乎因为我使用的是XMLHttpRequest选项而不是flask标准表单提交,所以我不能使用它。对于读取请求表单数据,有没有什么好的解析选项,或者我需要自己编写解析代码?在


Tags: 数据代码formvarcontentsummarypostdocument

热门问题