最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Outputing getJSON results once and they update every x seconds without the results repeating over and over - Stack

programmeradmin4浏览0评论

I had a previous problem solved on stackoverflow but the requirments of my project have changed so I need a new solution. To summerise I have a getJSON function that executes every 5 seconds to read for change in a JSON file. The problem I am having is outputting the data correctly. I want the data to output once but update every 5 seconds in case the user makes changes to the JSON file

Here is my code

 <script type="text/javascript">
$.ajaxSetup({
    cache: false
});
setInterval(function() {
    $.getJSON('names.json', function(data) {
        for (var i in data) {
            $('#one').append(data[i]);
        }
    });
}, 5000);

</script>

This getJSON function allows me to grab JSON data and append it to the start of a div. Then I refreash the function so that if the JSON data changes then the data changes in the div. The problem is that the data repeats itself every 5 seconds.

The unexpected result after 15 seconds

453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep

The result I want after 15 seconds

453545Beady little eyesLittle birds pitch by my doorstep

If I change the JSON 11 seconds when the script is running

"two": "Eyes"

The result I want to get after 15 seconds

453545 Eyes Little birds pitch by my doorstep

Rather than the actual result I get after after 15 seconds

453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
453545 Eyes Little birds pitch by my doorstep

Here is the JSON file I am using

{
  "one": "453545",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Hopefully I have made this as clear as possible

I had a previous problem solved on stackoverflow but the requirments of my project have changed so I need a new solution. To summerise I have a getJSON function that executes every 5 seconds to read for change in a JSON file. The problem I am having is outputting the data correctly. I want the data to output once but update every 5 seconds in case the user makes changes to the JSON file

Here is my code

 <script type="text/javascript">
$.ajaxSetup({
    cache: false
});
setInterval(function() {
    $.getJSON('names.json', function(data) {
        for (var i in data) {
            $('#one').append(data[i]);
        }
    });
}, 5000);

</script>

This getJSON function allows me to grab JSON data and append it to the start of a div. Then I refreash the function so that if the JSON data changes then the data changes in the div. The problem is that the data repeats itself every 5 seconds.

The unexpected result after 15 seconds

453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep

The result I want after 15 seconds

453545Beady little eyesLittle birds pitch by my doorstep

If I change the JSON 11 seconds when the script is running

"two": "Eyes"

The result I want to get after 15 seconds

453545 Eyes Little birds pitch by my doorstep

Rather than the actual result I get after after 15 seconds

453545Beady little eyesLittle birds pitch by my doorstep
453545Beady little eyesLittle birds pitch by my doorstep
453545 Eyes Little birds pitch by my doorstep

Here is the JSON file I am using

{
  "one": "453545",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Hopefully I have made this as clear as possible

Share Improve this question edited Jul 19, 2012 at 9:47 Esailija 140k23 gold badges279 silver badges328 bronze badges asked Jul 19, 2012 at 9:42 Matthew UnderwoodMatthew Underwood 1,5093 gold badges19 silver badges33 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

It's hard to decipher your question because there may be two different results of which one of them you're actually trying to achieve:

  • have only the latest JSON result displayed (no change history)
  • have only one JSON result per change displayed (history of changes)

The first one is simple and is as follows:

no history: Clear results before displaying them

Before you append your newly received results you have to clear previous ones.

<script type="text/javascript">

    $.ajaxSetup ({  
        cache: false  
    });  

    setInterval(function(){
        $.getJSON('names.json', function(data) {
            $('#one').empty();
            for(var i in data) {
                $('#one').append(data[i]);
            }
        });
    }, 5000);

</script>

change history: detect changes

Keeping change history has several different approaches:

  1. First one has been somehow summarized by rogal111. Although his solution may not be best especially when the format of your resulting JSON changes, because his code only work when JSON results have at least those 4 fields defined. If any of them's missing an undefined will get displayed and if any additional one is added it will be omitted.

  2. A more dynamic solution is provided by Trinh Hoang Nhu that works with any JSON object's properties.

  3. The third possible solution would be to call your Ajax URL by appending timestamp of the last change (names.json/timestamp) and if server sees that JSON has changed afterwards, it would send the object otherwise some default object would be sent over (i.e. false or null) which would indicate that no change has been made...

Just add to your JSON version tag and increment it each time you modifying JSON:

{ 
  "version": 12323
  "one": "453545",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Then in javascript check version tag before append:

<script type="text/javascript">
    var currentVersion=-1;
     $.ajaxSetup ({  

       cache: false  
    });  

   setInterval(function(){ $.getJSON('names.json', function(data) {

    if(data.version>currentVersion)
    {
      currentVersion=data.version;
      $('#one').append(data.one);
      $('#one').append(data.two);
      $('#one').append(data.three);
    }

   });

},5000);

</script>

Add an oldJson to pare with the new one. You will only out when they're different. Ex

var oldJSON = null;

function pareObject(a,b){//Simple parision
   for (i in a){
       if (!(i in b) || a[i] != b[i]){
          return false;
       }
   }
   return true;
}

setInterval(function() {
    $.getJSON('names.json', function(data) {
        //do the parision
        if (!pareObject(oldJSON, data)){
            for (var i in data) {
                $('#one').append(data[i]);
            }
        }
        oldJSON = data;; //Important
    });
}, 5000);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论