2014-10-10 31 views
0

首先,我需要承認我對Javascript的知識非常有限。爲了讓我的頁面內容在後臺刷新而無需使用jQuery的AJAX進行頁面刷新,我一直在努力工作。到目前爲止,我已經成功地獲得了需要通過div成功更新的所有內容變量。現在我還想根據div內的值更改td類。我更喜歡將這些信息存儲到一個可以帶到我的html頁面中的變量,我想知道我該如何實現這一目標。如何獲得一個存儲在json文件中的td類到一個html表格(使用ajax)

這裏是我的代碼簡化的例子:

PHP腳本,生成想要的變量和存儲(回波)它們爲JSON陣列(使用example.php)

$variable1 = 20; 

if ($variable1 > 50) { 
$variable1class="positive"; 
} else { 
$variable1class="negative"; 
} 

$array['variable1']  = $variable1; 
$array['variable1class'] = $variable1class; 

echo json_encode($array); 

HTML表其中變量從example.php生成的json中檢索:

<table> 
    <tr> 
     <td class='variable1class'> 
     <div id='variable1'></div> 
     </td> 
    </tr> 
</table> 

的javascript:

<script type="text/javascript"> 
    $(function() { 
    refresh(); 
    }); 

    function refresh() { 
     $.getJSON('example.php', function(data) { 
      $('div#variable1').html(data.variable1); 
     }); 
    setTimeout("refresh()",10000); 
    } 

上面的代碼不會完全刷新PHP頁面的背景和改變在HTML頁面中去DIV(變量1)內容。

如何插入td類(也存儲在json中)?提前很多

function refresh() { 
      $.getJSON('example.php', function(data) { 
       $('div#variable1').html(data.variable1); 
       $('td#variable1class').html(data.variable1class);    
      }); 
    setTimeout("refresh()",10000); 
} 

感謝:像下面的內容將是巨大的,但顯然沒有成功:)

javascipt的!

+0

使用console.log調試您的'數據'變量並在您的瀏覽器中查找任何錯誤。你給的語法應該工作,但不合邏輯,因爲你首先設置父A的孩子的HTML,然後設置父A本身的HTML – Flame 2014-10-10 15:01:27

回答

1
$('td.variable1class').addClass(data.variable1class); 
+0

非常感謝! – Roddeh 2014-10-10 15:12:09

相關問題