jQuery Ajax setTimeout JSON [英] jQuery Ajax setTimeout JSON

查看:75
本文介绍了jQuery Ajax setTimeout JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the jQuery AJAX to call JSON service. I am then spitting out the data to .html. I would like 2 things to happen. 1. I want a refresh button to refresh the data, not the whole page. 2. I want a setTimeout or setInterval (which ever works best) to update the data every 5 minutes or so. But refresh the page. How would I wrap the AJAX in a setTimeout or setInterval or refresh the data using a button and a timer every 5 minutes or so. I know this should be simple but I have not been able to get it to work. Thanks in advance.

以下是我的代码。

    $.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);
    }
});


推荐答案

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

This is what I did. I also found out from this post that the interval or timeout will race against the data load and the load. so I had to write it like this.

  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);
  });               

这篇关于jQuery Ajax setTimeout JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆