我引用了 w3schools.com 教程中的代码。我不知道我可能做错了什么,但是当我测试该网站时,我没有得到任何输出。没有任何。我将在下面发布代码。
<!DOCTYPE html>
<html>
<body>
<p id="par1"></p>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://xproshowcasex.api.channel.livestream.com/2.0/livestatus.json?callback=status";
xmlhttp.onreadystatechange=function() {
//readyState 4: request finished and response is ready
//status 200: "OK"
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
//var 'url' is defined above
xmlhttp.open("GET", url, true);
xmlhttp.send();
function status(response) {
var arr = JSON.parse(response);
if (arr.isLive = true) {
document.getElementById("par1").innerHTML = "live";
} else {
document.getElementById("par1").innerHTML = "offline";
}
}
</script>
</body>
</html>
我检查了 chrome 上的控制台日志,并给出了此错误:
XMLHttpRequest cannot load http://xproshowcasex.api.channel.livestream.com/2.0/livestatus.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
我看了直播论坛以及其他地方,没有人能给我提供可靠的解决方案。希望这里有人可以。感谢您的帮助!
--编辑--
我已经搜索了该网站,但没有找到解决我的问题的方法。如果有人知道哪里有解决方案,请发布链接,但据我所知,没有。众所周知,不同的代码有不同的问题,所以我希望得到答案而不是标记。
最佳答案
<!DOCTYPE html>
<html>
<head>
<meat charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<!--Livestream status script-->
<!-- CAN BE PLACED IN BODY -->
<script type="text/javascript">
$(document).ready(function () {
function getCrossDomainJson(url, callback) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?callback=?",
data: {
q: 'select * from xml where url="' + url + '"',
format: "json"
},
dataType: "jsonp",
success: callback
});
}
/*INSERT STREAM NAME INBETWEEN 'x' eg. http://xSTREAMNAMEx.channel-api.livestream-api.com/2.0/getstream*/
getCrossDomainJson("http://xhellgateospreyx.channel-api.livestream-api.com/2.0/getstream", function(data) {
console.dir(data);
if (data && data.query && data.query.results && data.query.results.channel) {
var statusTest = data.query.results.channel.isLive;
if (statusTest == "true") {
document.getElementById("par1").innerHTML = "online";
}
else {
document.getElementById("par2").innerHTML = "offline";
}
}
});
});
</script>
<!-- end of script -->
<body>
//par1 will change to online if stream is online; par2 will remain as unaffected
//par2 will change to offline if stream is offline; par1 will remain as unaffected
//I separated the p tags for testing purposes, but they can be combined
//if you do so, change the id in the if/else statements
<p id="par1">unaffected</p>
<p id="par2">unaffected</p>
</body>
</html>
如果您想要多个流状态,请选择从“getCrossDomainJson”到第一个“});”的代码并粘贴在两个 '});' 之间并替换“getElementById”中的流名称和标签。感谢所有帮助我解决这个问题的人!希望这对其他人有帮助。
关于javascript - 解析 JSON http 请求时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25560623/