javascript - 为什么它是一个空白然后是一个循环
问题描述
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 [我正在尝试访问的地址]”
解决方案
如果要实现原始 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:"..."
}
推荐阅读
- jenkins - 在多模块项目中找不到 jenkinsfile
- c++ - SQLite“在删除级联时”不在Qt中级联
- javascript - 使 mathquill 字段始终随光标滚动
- sql - Get all actors who have played in every film categor at least twice (Sakila DB)
- c++ - 让 3D 对象查看 3D 对象矩阵?
- c# - 创建报表winform
- javascript - 数据表没有自动更新
- java - JList 移动列表程序
- android - Android Studio gives error "Could not download builder.jar (com.android.tools.build:builder:3.2.0): No cached version available for offline mode"
- syntax - How to find out the right syntax in MariaDB Error Based SQL Injection?