【问题标题】:HTML with HTTP request: always returns 0带有 HTTP 请求的 HTML:总是返回 0
【发布时间】:2018-09-22 07:38:20
【问题描述】:

我是使用 JavaScript 的 HTML 新手:

我的代码是:

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();

我总是将xhr.status 设为 0?我用 Chrome 和 Edge 进行了测试。有什么问题?

【问题讨论】:

    标签: javascript html google-chrome httprequest microsoft-edge


    【解决方案1】:

    在请求完成之前,您正在查看 xhr.status。仅当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();
    

    也就是说,在所有主流浏览器上,XMLHttpRequest 已过时。相反,请使用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
        });
    

    如果您愿意,可以使用response.body,即ReadableStream,而不是使用.text.json 等助手。


    您说您仍然会使用更新的代码获得0 的状态。我能看到这种情况发生的唯一方法是,如果您发出跨域请求并被Same Origin Policy 阻止。您应该在 Web 控制台中得到一个相当明显的错误。如果是这种情况,请查看CORS(如果您控制另一端)或 JSONP 或使用服务器为您发出请求。那里有很多关于 SOP 和 CORS 的信息。

    【讨论】:

    • @ManigandanSeetharaman - 如果您查看 Web 控制台(这始终是要做的第一件事),您可能会看到与同源策略相关的错误 - 我已经在上面的末尾添加了一个注释。
    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多