我有一个从网址获取json对象的网页,然后将json对象转换为字符串。如果字符串为真,我希望div淡出,如果是假,我希望它保持不变。
来自网址的json对象是:{" description":"输入1","输入":" no",& #34;启用":true,"闹钟":false}
启用闹钟时,闹钟= true。但我需要经常检查警报是真还是假,所以我需要一个while循环或其他方法来不断检查url的json对象。
出于某种原因,我在下面的代码中使用的方法会导致分页。
当我取出while循环时,它运行正常,但我必须刷新浏览器以重新检查警报对象。
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
var data;
var r = true;
do {
$.ajax({
dataType: "json",
url: 'http://192.168.1.6/inputs/alarm.cgi',
data: data,
success: function (response) {
// begin accessing JSON data here
console.log(response.alarm);
var j = (JSON.stringify(response.alarm));
console.log(j);
if (j == 'true') {
$('div').fadeOut('slow');
}
}
});
} while (r == true);
});
</script>
</head>
<body>
<div></div>
</body>
</html>
CSS代码
div {
height: 100px;
width: 100px;
background-color: #FA6900;
border-radius: 5px;
}
答案 0 :(得分:5)
由于发出ajax请求的异步性质,您需要将“循环”变为“链”。
换句话说,在发出另一个ajax请求之前,你必须等待第一个ajax请求的结果。
var data;
var r = true;
function next(){
$.ajax({
dataType: "json",
url: 'http://192.168.1.6/inputs/alarm.cgi',
data: data,
success: successful
});
}
function successful (response) {
// begin accessing JSON data here
console.log(response.alarm);
var j = (JSON.stringify(response.alarm));
console.log(j);
if (j == 'true') {
$('div').fadeOut('slow');
}
// loop... assume some other logic controls "r".
// Otherwise this will be an infinite loop
// throttled by setTimeout.
if(r == true ){
// Delay calling next
setTimeout(next, 5000); // execute next in 5000ms (5 sec)
}
}
$(document).ready(next);
答案 1 :(得分:1)
您的浏览器正在冻结,因为您的代码运行速度非常快。你永远不会限制它打电话的速度,所以它的速度和计算速度一样快,现代计算机是一台令人难以置信的数学机器。虽然它不是“完美”的解决方案,但您可以使用setInterval而不是无限的while循环来减慢调用速度。
$(document).ready(function () {
this.apiCall = function() {
$.ajax({
dataType: "json",
url: 'http://192.168.1.6/inputs/alarm.cgi',
data: data,
success: function (response) {
// begin accessing JSON data here
console.log(response.alarm);
var j = (JSON.stringify(response.alarm));
console.log(j);
if (j == 'true') {
$('div').fadeOut('slow');
}
}
})
}
this.interval = setInterval(this.apiCall, 1000) //1 second intervals
}
编辑:bob的答案是以完美的同步性进行此调用的正式方法,但您可能仍在进行极其快速的API调用。如果它影响性能,我会推荐我的hacky方法。