返回局部视图的jQuery ajax

时间:2014-03-01 10:17:29

标签: jquery ajax asp.net-mvc

我有一个索引页面,显示有关不同系统的数据。我需要每2秒更新一次此页面。因此,我调用jQuery ajax来调用控制器的方法,该方法使用所请求的数据发送页面的局部视图。

在加载信息时,我有一个加载gif到用户反馈。

我遇到的问题是ajax调用正在运行(页面加载了信息)但在进入控制器方法之前,首先触发了ajax错误。

索引页

<div align="center" class="loader">
     <img src="@Url.Content("~/Images/loader.gif")"/>
</div>
 <div id="reportsContent">

 </div>

jQuery ajax call

var refreshInterval = @ViewBag.RefreshTime;
setInterval(function () { GetData() }, refreshInterval);

function GetData() {
    $.ajax({
        type: "POST",
        url: '@Url.Content("~/SystemReports/SystemReports")',
        //url: '@Url.Action("SystemReports")',
        dataType: "text",
        data : {},
        success: function (data) {
            $(".loader").hide();
            $('#reportsContent').html(data);
        },
        error : function() {
            alert('error');
        }
    });
};

如图所示我已尝试过@ Url.Action和@ Url.Content .. 我不知道为什么首先显示警报(&#39;错误&#39;),并且只有在页面正确加载所需数据后才会显示。

控制器

[HttpPost]
public PartialViewResult SystemReports()
{
    DataService.GetStatusData();

    SystemModel model = new SystemModel();
    Map(data, model);

    return PartialView("_ReportsContent", model);
}

我不知道为什么会触发错误并且$ .ajax仍然有效。也许有人可以帮助我?

1 个答案:

答案 0 :(得分:2)

错误是您无法在jQuery ajax API中使用ASP.NET代码。替换网址:

url: '/SystemReports/SystemReports'

现在可以使用了!您需要在通过jQuery发送Ajax请求时使用JavaScript API,而不是使用服务器端类,例如:Url等。它们不能在jQuery中工作,因为它们在jQuery Library中没有引用它们。

为了更准确地了解错误,您可以使用它来了解实际错误:

error: function(xhr, status, error) { 
  alert(xhr.responseText); 
}

这将警告正在抛出的错误,可能是404(Not Found)。