我的 Controller 中有以下代码:
int number = 0;
public JsonResult JsonData()
{
for (int i = 0; i < 21; i++)
{
number += i;
return Json(number, JsonRequestBehavior.AllowGet);
}
return Json(number, JsonRequestBehavior.AllowGet);
}
并在 View 中使用 jQuery Ajax 脚本循环:
<script type="text/javascript">
var tag = true;
$(document).ready(function () {
while (tag) {
$.ajax({
url: "@Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
console.log(data);
$('#counter').html('');
$('#counter').html(data);
if (data == 20) {
tag = false;
}
}
});
}
});
</script>
<div id="counter"></div>
我的目标是让 jQuery Ajax 不断从操作“JasonData”获取“数字”并将该数字打印到“DIV 标签”,但我当前的代码由于某种原因无法正常工作, - 结果是浏览器窗口不会如果我使用“while()”循环,则停止加载,如果我不使用“while()”循环,它只打印“number”变量的第一个值。
最佳答案
使用 setInterval/setTimeout 而不是 while 循环,因为连续运行的脚本会阻塞 UI,你可以使用回调机制来代替。
$(document).ready(function () {
var interval = window.setInterval(function(){
$.ajax({
url: "@Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
$('#counter').html(data);
if (data == 20) { //<-- make sure data has value 20 and is not an object or anything
window.clearInterval(interval);
}
}
});
}, 1000); //<-- Give interval in milliseconds here
});
<强> Demo
或者超时:
$(document).ready(function () {
makeAjaxCall();
});
function makeAjaxCall(){
$.ajax({
url: "@Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
$('#counter').html(data);
if (+data < 20) {
window.setTimeout(makeAjaxCall, 1000); //Duration in ms
}
}
});
}
<强> Demo
关于c# - 使用 MVC $.ajax() 一致地从 Controller 中的操作获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20111624/