跟踪已输出的JSON对象 [英] Track which JSON objects have been output

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

问题描述

我正在通过在加载页面时将索引设置为 randomNumber()来随机输出20个左右的JSON对象。



我正在刷新每个已经在timeInterval上输出的JSON对象。
要跟踪已输出的JSON项目,我通过 arrUsed.push [index]

$将每个项目的索引存储到数组中b
$ b

现在尝试编写将 update()单独的每个JSON对象的函数,目前我仍然坚持如何更新每个div使用尚未输出的新JSON对象的信息(推送到 arrUsed [] )。



这是我到目前为止的功能:

  function reloadItems(){
var itemTotal = $('div。 。项')长度; //最初加载的项目总数
var randomNumber = Math.floor(Math.random()* 301)//返回数字
index = randomNumber; //将要在JSON数据中使用的索引设置为随机数
}

该数组包含已经输出的索引全局声明: arrUsed = []; 在将页面加载存储到数组中时最初输出的每个项目,以便覆盖该部分。这是一个选择随机JSON对象的问题,检查以确保它不在数组中/尚未输出,然后更新页面上的div。



这里是 (主程序)

  • template.html (产品模板)

  • UK.top.20.html (JSON数据)

  • ticker.js (jQuery)

  • ticker.css (样式表)



  • 首先,我们应该存储template.html在我们的全局模板变量中并触发 getJson( )功能:

      template =''; 
    ....
    $(document).ready(function(){
    $ .get('template.html',function(html){template = html; getJson(); });
    });

    然后,我们将JSON存储到我们的数据变量并触发 initialize()函数:

     数据=''; // JSON数据将存储在这里
    myurl ='UK.top.20.html';
    ....
    函数getJson(){
    $ .getJSON(myurl,function(JSON){data = JSON; initialize();});
    }

    在这里,我们将调用 load() 功能3次,立即用数据填充我们的3个产品div。然后我们将 i 设置回 2 (这样它将首先更改第3个DIV),并安排 tick()在4.5秒内开火:

      tick_time = 4500; 
    ....
    function initialize(){//从前3
    开始(i = 1; i< 4; i ++){load(); }
    i = 2;
    setTimeout('tick()',tick_time);
    }

    在我们解释 load()之前 function,让我们来谈谈脚本底部的`String.prototype.f':

      String.prototype .f = function(){var args = arguments; return this.replace(/ \ {(\d +)\} / g,function(m,n){return args [n];}); }; 

    此函数类似于 String.Format(formatstring,arg1,arg2, arg3 ...)在C#或 sprintf($ formatstring,arg1,arg2,arg3 ...)在PHP中。这是一个例子:

      formatstring ='玫瑰是{0},紫罗兰是{1},String.Format {2}和{3}!'; 
    result = formatstring.f('red','blue','rocks','you');
    alert(result);

    正如你所看到的,这个 String.prototype.f 函数非常方便!



    load()函数要做的第一件事就是设置 rid = randomId(); 。我们接下来看一下 randomId()函数。它首先要做的是从1-20获取一个数字(基于我们的JSON数据的长度)。然后,它检查我们的看到的数组是否与我们的JSON数据大小相同,如果是 - 它将它设置回0.接下来它确保我们的最近没有看到 rid ,如果有,该函数会递归调用自身,直到获得唯一的随机ID。否则,我们在看到数组中存储 rid 并返回值。

      function randomId(){
    rid = Math.floor(Math.random()* data.results.length);
    if(seen.length == data.results.length){seen.length = 0; }
    if($ .inArray(rid,seen)== -1){
    seen.push(rid);
    返回摆脱;
    } else {return randomId(); }
    }

    接下来我们的 load()功能,我们设置 item plat 作为方便的快捷方式。 plat_html 是Platform元素的临时存储位置。 for循环查看我们的JSON中的所有Platform数据,并使用我们的String.Format函数来填充我们的plat_html字符串。



    最后,我们允许当前的i值(这是全局的)确定哪个 #product _ 得到更新, template.f 用JSON数据填充我们的模板,这是通过 .fadeIn()完成平滑的jQuery动画。

      function load(){
    rid = randomId();
    item = data.results [rid];
    plat = item.Platform;
    plat_html ='';
    for(var j = 0; j< plat.length; j ++){
    plat_html + = plat_fmt.f(
    plat [j] .Hardware,
    plat [j ]。市场
    );
    }
    $('#product_'+ i).html(
    template.f(
    item.Image,
    item.id,
    item) .AgeRating,
    item.WikiUrl,
    item.Title,
    item.Source,
    item.Genre,
    plat_html

    ) 。淡入();
    }

    最后,我们来看看递归 tick ()功能。它首先递增我们的全局 i 变量,并在它达到4时将其设置回1.然后我们执行动画 fadeOut()在我们的 #product _ 元素上等到它完成,直到我们再次调用 load()。然后,它安排自己再次在4.5秒内再次运行。

      function tick(){
    i ++; if(i == 4){i = 1; }
    $('#product_'+ i).fadeOut(function(){load();});
    setTimeout('tick()',tick_time);
    }

    就是这样!


    I'm outputting 20 or so JSON objects randomly by setting the index to a randomNumber() initially when the page is loaded.

    I'm refreshing each JSON object individually that has already been output on a timeInterval. To keep track of which JSON items have been output I am storing the index of each item into an array via arrUsed.push[index]

    Now trying to write the function that will update() each JSON objects individually and am currently stuck on how I can update the each div with the information from a new JSON object that has not already been output (pushed to the arrUsed[]).

    Here's the function I have so far:

    function reloadItems() {
        var itemTotal = $('div.item').length; // Total number of items loaded initially
        var randomNumber=Math.floor(Math.random()*301) //returns number 
        index = randomNumber; // Sets index to be used in JSON data to random number
    }
    

    The array that contains the already output index's is declared globally: arrUsed = []; Each item that is output initially when the page load is being stored to the array fine, so that part is covered. It's a matter of choosing a random JSON object, checking to ensure it is not in the array/not been output already, and then updating the div on the page.

    Here's the previous question that has led me to this point

    解决方案

    Here's a working example of a JSON/AJAX Ticker:

    Per twhyler's specification, it randomly swaps an item every 4.5 seconds, keeping track of ones that have already been seen. Once they've all been seen, it starts over again:

    Code Files:

    First, we should store template.html in our global template variable and fire the getJson() function:

    template = '';
    ....
    $(document).ready(function () {
        $.get('template.html', function(html) { template = html; getJson(); });
    });
    

    Then, we'll store the JSON into our data variable and fire the initialize() function:

    data = ''; // JSON data will be stored here
    myurl = 'UK.top.20.html';
    ....
    function getJson() { 
    $.getJSON(myurl, function (JSON) { data = JSON; initialize(); });
    }
    

    Here, we'll call the load() function 3 times to populate our 3 product div's with data right away. Then we set i back to 2 (that's so it will change the 3rd DIV first), and schedule tick() to fire in 4.5 seconds:

    tick_time = 4500;
    ....
    function initialize() { // Start with the first 3
    for (i = 1; i < 4; i++) { load(); }
    i = 2;
    setTimeout('tick()', tick_time);
    }
    

    Before we explain the load() function, let's talk about `String.prototype.f' at the bottom of the script:

    String.prototype.f = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; }); };
    

    This function works similar to String.Format(formatstring, arg1, arg2, arg3...) in C# or sprintf($formatstring, arg1, arg2, arg3...) in PHP. Here's an example:

    formatstring = 'Roses are {0}, Violets are {1}, String.Format {2} and so do {3}!';
    result = formatstring.f('red', 'blue', 'rocks', 'you');
    alert(result);
    

    So as you can see, this String.prototype.f function comes in very handy!

    The first thing the load() function will do is set rid = randomId();. Let's take a look at the randomId() function next. The first thing it does is get a number from 1-20 (based on the length of our JSON data). Then, it checks to see if our seen array is the same size as our JSON data, and if it is - it sets it back to 0. Next it makes sure that our rid hasn't been seen recently, and if it has, the function recursively calls itself again till it gets a unique random id. Otherwise, we store the rid in our seen array and return the value.

    function randomId() {
    rid = Math.floor(Math.random() * data.results.length);
    if (seen.length == data.results.length) { seen.length = 0; }
    if ($.inArray(rid, seen) == -1) {
        seen.push(rid);
        return rid;
    } else { return randomId(); }
    }
    

    Next in our load() function after getting that random ID, we setup item and plat as convenient shortcuts. plat_html is a temporary storage place for the Platform elements. The for-loop looks at all the Platform data in our JSON and uses our String.Format function to fill our plat_html string.

    Finally, we allow the current value of i (which is global) determine which #product_ gets updated, and template.f fills our template with JSON data which is done with a smooth jQuery animation thanks to .fadeIn().

    function load() {
    rid = randomId();
    item = data.results[rid];
    plat = item.Platform;
    plat_html = '';
    for (var j = 0; j < plat.length; j++) {
        plat_html += plat_fmt.f(
            plat[j].Hardware, 
            plat[j].Market
        );
    }
    $('#product_' + i).html(
        template.f(
            item.Image, 
            item.id, 
            item.AgeRating,
            item.WikiUrl,
            item.Title,
            item.Source,
            item.Genre,
            plat_html
        )
    ).fadeIn();
    }
    

    Lastly, let's take a look at the recursive tick() function. It begins by incrementing our global i variable and setting it back to 1 when it reaches 4. Then we perform an animated fadeOut() on our #product_ element and wait till it's finished till we call load() again. Then, it schedules itself to run again in another 4.5 seconds.

    function tick() {
    i++; if (i == 4) { i = 1; }
    $('#product_' + i).fadeOut(function() { load(); });
    setTimeout('tick()', tick_time);
    }
    

    That's it!

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

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