c# - 使用 MVC $.ajax() 一致地从 Controller 中的操作获取数据?

标签 c# javascript asp.net-mvc jquery

我的 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/

相关文章:

c# - 围绕现有 XDocument 包装附加元素

c# - 缺少编译器所需的成员 'microsoft.csharp.runtimebinder.binder.convert'

javascript - 对于每个函数。先对 2 做一些事情,然后再对其余的做其他事情?

asp.net - 从我的模型类中捕获异常的最佳方法

C# GC 委托(delegate)?

c# - 在后台运行应用程序 : Windows phone 8 phonegap

javascript - 使用javascript从中心调整大小,裁剪图像

javascript - jQuery z-index 不起作用

asp.net-mvc - 数据库优先 - EntityType xxx 没有定义键。定义此 EntityType 的键

c# - MvcSiteMapProvider 中各个项目的可见性?