从javascript获取当前页面http状态

xe55xuns  于 2023-06-20  发布在  Java
关注(0)|答案(6)|浏览(174)

有什么方法可以从javascript中获取当前网页的http状态吗?
花了一些时间在网上搜索,但没有运气在所有...看起来这是不可能的,但想检查堆栈溢出,也许一些花哨的解决办法。
(从服务器提供它作为响应主体的一部分是不可接受的,状态应该只能通过http标头获得)

0vvn1miw

0vvn1miw1#

这是不可能的,对不起。

tkclm6bt

tkclm6bt2#

是的你可以
只需请求相同的页面,即。URI,使用XMLHttpRequest。假设你的页面在/stop.php上的stop.php中,你可以做如下操作:

<script>
function xhrRequest(){            
            console.log(this.status);
            // Do some logic here. 
        }
function getReq(url){
            var oReq = new XMLHttpRequest();
            oReq.addEventListener("load", xhrRequest);
            oReq.open("GET", url);
            oReq.send();
        }
getReq("/stop.php");
</script>

查看此DEMO

🕯注意:

请注意,它是页面的副本,而不是页面本身。我已经在一个页面上使用了这个解决方案,当请求来自未经授权的IP地址时,服务器可能会生成禁止的HTTP状态代码,所以这里的条件非常简单,原始页面和您模拟其访问的复制页面之间没有太大的区别。

goucqfw6

goucqfw63#

作为一个衬垫:

fetch(location.href).then(response => console.log(response.status));

这是异步的,如果你需要一个同步的解决方案,使用XMLHttpRequest(如另一个答案)和async:false或使用async/await,它感觉是同步的,但在后台仍然是异步的。

或者

没有额外调用的方法需要在服务器端的页面中包含状态代码(例如在 meta标签中),然后通过JavaScript在客户端读取它。
Java + Thymeleaf:

<meta name="statuscode" th:content="${#response.status}">

PHP(未验证):

<meta name="statuscode" content="<?php echo http_response_code() ?>">
twh00eeo

twh00eeo4#

var xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href, false);
xhr.send(null);
console.log(xhr.status);
j2cgzkjk

j2cgzkjk5#

它并不漂亮,但你可以用途:

t = jQuery.get(location.href)
    .success(function () { console.log(t.status) })
    .error(function()    { console.log(t.status) });

当Eric说,这个解决方案将从同一个页面发出一个新的请求,并且不显示当前请求的状态。

siv3szwd

siv3szwd6#

你只能检查页面加载的状态try:var x = document.readyState; x的结果可能是:五个值之一:

uninitialized - Has not started loading yet
loading - Is loading
loaded - Has been loaded
interactive - Has loaded enough and the user can interact with it
complete - Fully loaded

相关问题