简体   繁体   English

XMLHttpRequest使用POST打开时发送GET请求

[英]XMLHttpRequest Sending GET Request When Opening with POST

I am writing a basic function on my webpage, to POST data to another page on my webserver, however whenever I submit using this function, the server reports having received a GET request with no form data. 我在网页上编写了一个基本功能,以便将数据发布到Web服务器上的另一个页面,但是,每当我使用此功能提交时,服务器都会报告已收到没有表单数据的GET请求。

Unfortunately, I am completely at a loss when it comes to sorting this out, as I have no clue what is causing it. 不幸的是,在整理问题时我完全不知所措,因为我不知道是什么原因造成的。

function submit_function(event){
    event.preventDefault();
    var req = new XMLHttpRequest();

    var fd = new FormData();
    fd.append("username", "username");
    fd.append("password", "password");

    req.open("POST", "/auth/login", true);
    req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    req.send(fd);

    return false;
}

Any help or insight at all is appreciated, it is getting late and there is a good chance I'm missing something obvious. 任何帮助或见解都值得赞赏,它来晚了,我很可能会错过一些明显的东西。

Issue was caused by a form submission interfering with the request, because it was nested as such. 问题是由表单提交干扰请求引起的,因为它是嵌套的。

document.getElementById("formid").onsubmit = function(e){ submit(e); }

The usual reason for this is that your code is triggered by a form submission, and you're not cancelling the form submission, so the browser sends the form (as a GET, apparently there's no type="POST" on the form element) and that prevents the ajax call from actually being made (even if your code runs to start it, tearing down the page to replace it with the result of the form submission prevents it from getting very far). 通常的原因是您的代码是由表单提交触发的,并且您没有取消表单提交,因此浏览器发送表单(作为GET,显然表单元素上没有type="POST" )并且这会阻止ajax调用的实际执行(即使您的代码运行启动了它,也要撕毁页面以将其替换为表单提交的结果来阻止它)。 Just ensure you're preventing the form submission ( event.preventDefault() ). 只要确保您阻止表单提交( event.preventDefault() )。

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

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