简体   繁体   English

XMLHttpRequest不发送

[英]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. 在控制台中也记录为0。 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. 我一直在这里关注文档: https : //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest ,尝试了无数次调整,并且控制台中没有任何错误。 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. 我的服务器上的PHP绝对可以正常工作,因为我能够从本地html文件成功过帐数据。

Since the AJAX request is asynchronous, you need to handle it through a callback onreadystatechange . 由于AJAX请求是异步的,因此您需要通过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 有关更多信息: https : //www.w3schools.com/js/js_ajax_http_response.asp

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

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