每 5 秒从数据库中获取数据并通过 AJAX 将其发送到视图

Get Data from DB every 5 sec and send it through AJAX to Views

我需要一些帮助。我想用 db(mssql) 中的数据每 5 秒更新一次 Google 地图标记。

我有 JsonResult 返回表格列表:

    [System.Web.Mvc.HttpGet]
    JsonResult LoadDB()
    {
        EagleDBEntities db = new EagleDBEntities();

        return Json(db.Coordinates.ToList(), JsonRequestBehavior.AllowGet);
    }

我的 Ajax 代码在视图中

        function getData() {

            $.ajax({
                type: "GET",
                url: "Home/LoadDB",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {

                    $.each(data.items, function(item) {
                        alert('long:'+item.longitude +' lat:'+item.latitude);
                    });
                },
                error: function (response) {

                    alert('error');
                }
            });

在我收到错误警报时,我没有从数据库接收数据:(

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:7279/Home/LoadDB

您只需像这样设置一个 javascript 定时器:

setInterval(function(){ getData(); }, 3000);

我修好了。

HomeController.cs:

    [HttpGet]
   public JsonResult LoadDB()
    {
        EagleDBEntities db = new EagleDBEntities();
        var cor = db.Lokalizacja          
           .Select(a => new
           {
               szerokosc = a.szerokosc,
               dlugosc = a.dlugosc
           });

        return Json(cor, JsonRequestBehavior.AllowGet);
    }

Maps.cshtml:

        function getData() {

        var counter = 0;
        interval = window.setInterval(function () {
            counter++;

            $.ajax({
                type: "GET",
                url: "LoadDB",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, item) {

                        moveMarker(item.szerokosc, item.dlugosc);

                    });
                },
                error: function (response) {

                    alert('eror');
                }
            });



            marker.setPosition(pos);
            if (counter >= 1000) {
                window.clearInterval(interval);
            }
        }, 10);




    };