为什么要空白然后循环

时间:2018-10-22 19:22:37

标签: javascript html

ip.txt包含IP地址和Web应用程序的端口。我希望按钮能够读取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 [尝试访问的地址]”的窗口

1 个答案:

答案 0 :(得分:0)

如果要实现原始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;
      }
    }
  });
}

顺便说一句,作为一种优化,BTW使用json格式来代替,它更有意义地获取格式化数据而无需解码和编码:

ip.json的内容:

{
 uri:"..."
}