简体   繁体   English

带有HTTP请求的HTML:始终返回0

[英]HTML with HTTP request: always returns 0

I am new to HTML with JavaScript: 我不熟悉HTML和JavaScript:

My code is: 我的代码是:

var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.status);
    }
    else{
        alert(xhr.status);
    }
}
xhr.open('GET', "http://localhost:8080/hello", true);
xhr.send();

I always get xhr.status as 0? 我总是将xhr.status设为0? I an testing with Chrome and Edge. 我使用Chrome和Edge进行了测试。 What is the issue? 有什么问题

You're looking at xhr.status before the request is complete. 您在请求完成之前正在查看xhr.status Only check status when readyState is 4 : 仅在readyState4时检查status

var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
    if (xhr.readyState == 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
            // All good
            console.log(xhr.status);
        }
        else {
            // Something went wrong
            alert(xhr.status);
        }
    }
}
xhr.open('GET', "http://localhost:8080/hello", true);
xhr.send();

That said, on all major browsers, XMLHttpRequest is obsolete. 也就是说,在所有主要的浏览器上, XMLHttpRequest已过时。 Instead, use fetch : 相反,请使用fetch

fetch("http://localhost:8080/hello")
    .then(response => {
        if (!response.ok) {
            throw new Error(response.status);
        }
    })
    .then(response => {
        // Read the body of the response
        return response.text(); // or .json(), .arrayBuffer(), .blob(), .formData()
    })
    .then(data => {
        // All good, use the data
    })
    .catch(error => {
        // Handle the error
    });

If you prefer, instead of using the .text , .json , etc. helpers, you can use response.body , which is a ReadableStream . 如果愿意,可以使用response.body (它是ReadableStream来代替.text.json等帮助器。


You've said you're still getting a status of 0 with the updated code. 您已经说过,更新后的代码仍然处于0状态。 The only way I can see that happening is if you're making a cross-origin request and being prevented by the Same Origin Policy . 我能看到的唯一方法是,如果您正在发出跨域请求,并且受到相同来源策略的阻止。 You should be getting a fairly clear error in the web console. 您应该在Web控制台中得到一个非常明确的错误。 If that's the case, look into CORS (if you control the other end) or JSONP or using a server to make the request for you. 如果是这种情况,请查看CORS (如果您控制另一端)或JSONP或使用服务器为您提出请求。 There's a lot of information about the SOP and CORS out there. 那里有很多有关SOP和CORS的信息。

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

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