首页 > 解决方案 > 为什么它是一个空白然后是一个循环

问题描述

ip.txt包含 Web 应用程序的 IP 地址和端口。我希望一个按钮能够读取内容ip.txt然后将 href 设置为那个。我一直在尝试用很多不同的方法来做这件事,但我无法让它发挥作用。

这是我尝试过的最新一个(刚刚打开about:blank


代码:

  <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Quick deploy</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>    
    </head>
        <body>
            <style>
                .center {text-align: center; position: absolute;}
            </style>
            <script>
            function a() {
                var client = new XMLHttpRequest();
                client.open('GET', 'ip.txt');
                client.onreadystatechange = function() {
                    window.open(client.responseText);
                }
                client.send();
            }
            </script>
            <a class="btn btn-outline-danger center" href="#" onclick="a();">Connect to instance</a>
        </body>
    </html>

我收到错误:

未捕获的 DOMException:无法在“窗口”上执行“打开”:无法打开带有无效 URL 的窗口“%3 [我正在尝试访问的地址]”

标签: javascripthtml

解决方案


如果要实现原始 AJAX 请求,则必须检查 xhr 状态:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        window.location.href = xhr.responseText;//here is your data
    }
}
xhr.open('GET', 'ip.txt');
xhr.send();

您启用了 JQuery,为什么不$.ajax改用,更有意义。

function a(){
  $.ajax({
    url:'ip.txt',
    success: function (data){
      //data is content of ip.txt
      debugger;//check what's inside.
      if(!!data){
        window.location.href = data;
      }
    }
  });
}

顺便说一句,作为一种优化,使用json格式代替,在不解码和编码的情况下获取格式化数据更有意义:

ip.json 的内容:

{
 uri:"..."
}

推荐阅读