简体   繁体   中英

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.

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). Just ensure you're preventing the form submission ( event.preventDefault() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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