data.txt
{ "number1":1200, }
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> 大盘指数:<span id="number" style="color: red;font-size: 36px;">1000</span> <script src="../js/jquery.js"></script> <script> $(function() { //每隔1000毫秒,发出一次ajax请求,响应数据 setInterval(function(){ $.getJSON('data.txt',function(data) { $('#number').text(data.number1); }); },1000); }); </script> </body> </html>
wh_data.txt
[ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]
wh_index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="../js/jquery.js" ></script> </head> <body> <script> $(function(){ /*在Chrome中,它显示在控制台下面的错误: Uncaught TypeError: Cannot use 'in' operator to search for '156' in [{"id":"1","tagName":"apple"}... 解决方案:JSON字符串转换为JavaScript对象。 要修复它,通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。 */ var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]'; setTimeout(function(){ $.each(JSON.parse(json), function(idx, obj) { //console.log(obj.tagName); }); },"1000"); //使用js处理json格式的txt文件 setTimeout(function(){ $.get("wh_data.txt",function(data){ $.each(JSON.parse(data), function(idx, obj) { //console.log(idx+"---"+obj.tagName); }); }); },"1000"); /* $.getJSON与$.get区别: * $.getJSON已经明确是获取JSON格式的文件数据 * $.get是获取整个文件内容,若是JSON格式,还需要处理解析成JSON格式 * * 若在$.getJSON中,再次将回调函数的数据解析的话,会报如下错误 * * VM308:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) */ setTimeout(function(){ $.getJSON("wh_data.txt",function(data){ $.each(data, function(idx, obj) { //console.log(obj.tagName); }); }); },"1000"); //问题,如何在轮询推送的同时,每次推送的是下一个JSON格式中的元素 var num=0; setInterval(function(){ $.getJSON("wh_data.txt",function(data){ $.each(data, function(idx, obj) { if(0==num){ //num: 1 idx 0---apple console.log("num: "+num+" idx "+idx+"---"+obj.tagName); }else if(idx==num){ //num: 1 idx 0---apple console.log("num: "+(num%5)+" idx "+idx+"---"+obj.tagName); } }); }); num++; },"1000"); }); </script> </body> </html>