Nei*_*l W 2 ajax jquery asp.net-mvc-4
我有一个具有子部分视图的视图(在主_Layout.cshtml视图中).
我在主视图上有按钮(class = get-widgets),它应该调用控制器并检索一些数据以填充到子部分视图(_WidgetListPartial).这工作正常......一次.点击事件注册似乎在第一次点击后丢失,第二次和后续点击什么都不做.
我还注意到,在调用运行时(没有执行延迟的thread.sleep(2000)),数据加载文本没有出现.
主视图中的代码:
Index.cshtml
@model MyApp.Models.WidgetViewModels.MainWidgetViewModel
@{ ViewBag.Title = "Widget Control Panel"; }
<div class="jumbotron">
<h1>@ViewBag.Title.</h1>
</div>
<div class="row">
<div class="col-md-6">
<h2>Widgets</h2>
<button class="btn btn-default pull-right get-widgets" data-loading-text="Loading ...">Refresh</button><br />
<div class="widgets">
@{Html.RenderPartial("_WidgetListPartial", Model.Widgets);}
</div>
<p>@Html.ActionLink("Create Widget", "Create", "Widget")</p>
</div>
</div>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script>
$(document).ready(function () {
$(document).on('click', '.get-widgets', function (e) {
var $btn = $(this).prop('disabled', true);
$.ajax('@Url.Action("GetWidgets", "Desktop")').done(function (html) {
$('.widgets').html(html);
}).always(function () {
$btn.prop('disabled', false);
alert('You pressed refresh ...');
});
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
更新**
经过进一步分析后,看来click事件实际上正在触发.我通过在被调用的函数中添加一个javascript"alert"方法证明了这一点(见上文).所以,现在看来真正的问题是"$ .ajax(..."调用没有在第二次和后续点击时执行(除非我在点击之间清除浏览器缓存).
所以,我现在的问题似乎是"当$ .ajax调用实际上不知道它需要从服务器检索的数据是什么时,为什么"$ .ajax"调用基于缓存失败(或被抑制)?会变得与众不同.
最终更新和决议
问题的原因似乎是ajax调用将"缓存",如果它再次使用完全相同的URL执行(在我的情况下它会执行,因为结果的变化不是基于ajax调用本身的性质,但基于底层数据存储库可能已经改变状态的事实).因此,从浏览器的角度来看,来自ajax调用的请求是相同的.
答案是添加$ .ajaxSetup({cache:false});
完整(工作版)如下:
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script>
$.ajaxSetup({ cache: false }); // NEEDED TO ENSURE THE AJAX CALL WILL RUN ON EVERY CLICK, AND NOT JUST THE FIRST
$(function () {
$(document).on('click', '.get-widgets', function (e) {
var $btn = $(this).prop('disabled', true);
$.ajax('@Url.Action("GetWidgets", "Desktop")').done(function (html) {
$('.widgets').html(html);
}).always(function () {
$btn.prop('disabled', false);
});
e.preventDefault();
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
将脚本放在jquery ready函数中:
$(function() {
$(document).on('click', '.get-widgets', function (e) {
var $btn = $(this).prop('disabled', true);
$.ajax('@Url.Action("GetWidgets", "Desktop")').done(function (html) {
$('.widgets').html(html);
}).always(function () {
$btn.prop('disabled', false);
});
});
});
Run Code Online (Sandbox Code Playgroud)
也尝试添加它以确保没有进行缓存:
$.ajax({
url: "test.html",
cache: false
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6037 次 |
最近记录: |