XMLHttpRequest.senddata未将数据传递到Django视图函数

问题描述

使用纯Javascript,我的目标是重新创建jQuery的.autocomplete()函数,以在用户输入搜索栏输入内容显示建议列表。

我编写了侦听输入元素(即搜索栏)上的“键盘输入/更改/粘贴/输入”事件的代码。当用户输入内容时,我希望使用XMLHttpRequest GET(或POST)请求,该请求会将到目前为止的用户输入(以及有关搜索上下文的信息-不相关)传递给视图函数,后者将依次过滤对象的模型包含到目前为止的用户输入,并将JSONResponse列表中的那些对象返回到XMLHttpRequest,以便我可以在网页上显示建议。

我尝试同时使用GET和POST请求,但是希望使用XMLHttpRequest.send(data)发送到视图函数的数据似乎从未传递到视图函数,因此阻碍了我的进度。在所有尝试中,打印request.POST(或request.GET)都将QueryDict空:

下面是一些代码段:

\\ The below JS code is run on once the page is ready,i.e fully loaded
addListenerMulti(query,"propertychange change click keyup input paste",function () {
            // check if value has changed...
            if (query.value != oldVal) {
                oldVal = query.value;
                var context_object = JSON.stringify({
                    "query_so_far": encodeURI(query.value),"search_context": encodeURI(document.getElementById("filter").value)
                });
              
                try {
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET",'url-for-view-function');
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            console.log(xhr.response);
                        } else if (xhr.status === 500) {
                            console.log(xhr.response);
                        }
                    }
                    xhr.send(context_object);
                } catch (e) {
                    console.log(e);
                }
            }
        })

我怎么了?我该怎么解决?谢谢。

解决方法

我通过使用GET请求解决了这个问题。为了发送数据,我将其包含在XMLHttpRequest.setRequestHeader函数中,该函数采用一个键,值对。需要注意的是,密钥应采用“ Xxxx-Yyyy”或“ Xxxx”格式。

try {
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET",'autocomplete');
                    xhr.setRequestHeader("Query-Str",encodeURI(query.value));
                    xhr.setRequestHeader("Search-Context",encodeURI(document.getElementById("filter").value))
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            console.log(xhr.response);
                        } else if (xhr.status === 500) {
                            console.log(xhr.response);
                        }
                    }
                    xhr.send(context_object);
                } catch (e) {
                    console.log(e);
                }