使用Javascript或Jquery操作API Feed

时间:2012-06-30 03:39:03

标签: javascript jquery json api

我是初学者,所以如果这个问题是初级的,我会道歉。

我有一个数据api,它以这种格式返回一个JSON对象:

{"Variable": "Number", "Variable2": "Number2"}; //(yes the number is returned as a string)

我想创建一个页面,其中来自对象的值(“Number”&“Number2”)不断更新,因为值不断变化,但整个页面不需要刷新。

http://sendgrid.com就是我想要做的一个很好的例子。

任何帮助都会很棒!

2 个答案:

答案 0 :(得分:1)

处理持续更改的数据的方法是使用setTimeout。还有另一个名为setInterval的方法,但最好将setTimeout与递归函数一起使用。这样,如果操作时间超过预期,计时器将不会失去同步。通过例子证明:

function updateCounter() {
 var timer; 

 document.getElementById("counter").innerText(data.Variable);

 timer = setTimeout(updateCounter, 50);

}

答案 1 :(得分:0)

您可以使用setInterval()向您的API发送请求,并使用您的数据更新目标元素。

只是一个例子:

function updater() {
  $.ajax({
    url: 'src_to_script',
    dataType: 'json',
    sucess: function(data) {

       // updating your target elements
       $('#some_item1').text( data.Variable);
       $('#some_item2').text( data.Variable2);

       // call updater with 5 seconds interval
       setInterval(updater, 5000);

    }
  });
}

// initial call to updater
updater();