簡體   English   中英

始終從MVC $ .ajax()中的控制器中的操作獲取數據?

[英]Consistently get data from action in controller with in MVC $.ajax()?

我的控制器中有以下代碼:

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);
    }

並在視圖中循環使用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
});

演示

或超時:

$(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
                    }
                }
            });
        }

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM