简体   繁体   中英

XMLHttpRequest Not Sending

This is part of the code for the extension:

let url = "https://mywebsite.com/data.php";
function newRequest() {
    var client = new XMLHttpRequest();
    client.open("POST", url, true);
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send("status=true");
    console.log(client.status);
}
newRequest();

Which also logs 0 in the console. I've been following the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest , trying countless tweaks, and there aren't any errors in the console. Not really sure what the issue could be.

The PHP on my server definitely works since I was able to POST the data successfully from a local html file.

Since the AJAX request is asynchronous, you need to handle it through a callback onreadystatechange .

The code should be like this

let url = "https://mywebsite.com/data.php";
function newRequest() {
    var client = new XMLHttpRequest();
    client.onreadystatechange = function() {
        console.log(this.readyState) // should be 4
        console.log(this.status) // should be 200 OK
        console.log(this.responseText) // response return from request
    };
    client.open("POST", url, true);
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send("status=true");
    console.log(client.status);
}
newRequest();

Hope this helps.

For More Info: https://www.w3schools.com/js/js_ajax_http_response.asp

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