首先是我的代码
$.getJSON("./posts/vote/" + postId + "/1", null, function(result) {
if (result.result == true)
$("#pst" + postId + " > .pstside > .rank > .score").html(result.voteCount);
});
我有一堆按钮,每个按钮带有代码,可以从ASP.Net MVC控制器操作中获得一些投票结果。
这在第一次单击按钮时效果很好,但如果再次单击该按钮则没有任何反应。什么都没有到达服务器。
我正在测试FireFox。
出了什么问题?某种奇怪的缓存?因为请求第二次永远不会到达我的控制器,所以javascript似乎执行正常但仍然返回旧值。
答案 0 :(得分:18)
听起来像是一个浏览器缓存问题(如果我非常确定IE正在发生这种情况),您可能希望使用$.ajax并将缓存选项设置为false,因为它默认为false对于dataType script
和jsonp
:
$.ajax({
type: "GET",
url: "./posts/vote/" + postId + "/1",
success: function (result) {
if (result.result == true)
$("#pst" + postId + " > .pstside > .rank > .score").html(result.voteCount);
},
dataType: "json",
cache: false
});
或者你可以在使用$ .getJSON之前使用$.ajaxSetup为所有jQuery Ajax函数全局设置该选项:
$.ajaxSetup({ cache: false });
编辑:您可以执行返回JSON的POST请求,如下所示:
$.post("./posts/vote/" + postId + "/1",
function (result) {
if (result.result == true)
$("#pst" + postId + " > .pstside > .rank > .score").html(result.voteCount);
}, "json");
如果你打算做很多 postJSON 请求,你可以自己创建函数:
jQuery.postJSON = function(url, data, callback) {
jQuery.post(url, data, callback, "json") ;
};
你可以像$ .getJSON
一样使用它答案 1 :(得分:2)
由于您正在进行“GET”,因此某些缓存(在浏览器,代理/中介或服务器上)可能是个问题,这听起来并不合理。如果要更改数据(“不断返回旧值”),也许尝试使用“POST”。或者在查询中引入一些随机组件。
答案 2 :(得分:2)
是的,$.ajaxSetup({ cache: false });
确实解决了问题!我的应用程序是使用MVC 2.代码如下:
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajaxSetup({ cache: false });
$('#btnApplyForm').click(function () {
$("#applyForm").html("Loading...");
$("#divApplyForm").dialog("open");
var id = $('#applyFormID').attr("value");
$.get('<%= Url.Content("~/Applying/FillApplyForm/") %>' + id,
function (response) { $("#intakeForm").html(response); }
);
return false;
});
$("#divApplyForm").dialog({
title: "Application Form",
autoOpen: false,
bgiframe: true,
modal: true,
width: 600,
height: 540
});
});
</script>
答案 3 :(得分:0)
您也可以对GET请求执行相同操作,只需在请求结尾添加时间戳,例如,请参阅以下示例请求
http://www.abc.com/api/v1/votes?user=123&tag=jQuery&的 _timestamp = 1234421352 强>
这样,浏览器就不会缓存您的请求,因为每次调用时url都会更改。您可以轻松地从Javascript获取时间戳。此外,您无需在服务器端处理此时间戳,但这取决于您自己的判断。