jQuery Ajax setTimeout JSON

我正在使用jQuery AJAX来调用JSON服务。 然后我将数据吐出到.html。 我想要做两件事。 1.我想要一个刷新按钮来刷新数据,而不是整个页面。 2.我想要一个setTimeout或setInterval(效果最好)每5分钟左右更新一次数据。 但刷新页面。 如何将AJAX包装在setTimeout或setInterval中,或者每隔5分钟左右使用一个按钮和一个计时器刷新数据。 我知道这应该很简单,但我无法让它发挥作用。 提前致谢。

以下是我的代码。

$.ajax({ type: "POST", url: "/myservice.asmx/WebMethod", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { var myval = msg.d; // $('#jsonstring').html(myval); var obj = jQuery.parseJSON(myval); $('#Data1').html(obj.DataOne); $('#Data2').html(obj.DataTwo); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.statusText); alert(xhr.responseText); alert(xhr.status); alert(thrownError); } }); 

这就是我所做的。 我还从这篇文章中发现,间隔或超时将与数据负载和负载竞争。 所以我不得不这样写。

  function myFunction() { $.ajax({ type: "POST", url: "/myservice.asmx/WebMethod", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { var myval = msg.d; // $('#jsonstring').html(myval); var obj = jQuery.parseJSON(myval); $('#Data1').html(obj.DataOne); $('#Data2').html(obj.DataTwo); //TO SET THE TIMEOUT FOR DATA TO LOAD setTimeout(function(){ yourFunction(); }, 300000); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.statusText); alert(xhr.responseText); alert(xhr.status); alert(thrownError); } }); } $(document).ready(function(){ //Load on Doc Ready myFunction(); //Reload on button click $('#myBtn').click(function(){ myFunction(); }); //TO SET THE TIMEOUT FOR DATA TO LOAD - Need both in the success and here. setTimeout(function(){ myFunction(); }, 2000); }); 
 function rData(){ $.ajax({ type: "POST", url: "/myservice.asmx/WebMethod", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { var myval = msg.d; // $('#jsonstring').html(myval); var obj = jQuery.parseJSON(myval); $('#Data1').html(obj.DataOne); $('#Data2').html(obj.DataTwo); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.statusText); alert(xhr.responseText); alert(xhr.status); alert(thrownError); } }); } setInterval(rData,300000);  

假设您的ajax调用正在运行,您可以将其放入函数中并在计时器/间隔中引用它。

 function Refresh() { /* your ajax code */ } setInterval(Refresh, 300000); // five minutes, in milliseconds $("#MyButton").click(Refresh); 
 function refreshContent() { $.ajax..... } function refreshContentTimer() { refreshContent(); setTimeout(refreshContentTimer, 300000); // 5 min } $(function () { setTimeout(refreshContentTimer, 300000); $("#refreshButton").click(refreshContent); }