2015-08-28 131 views
2

我想知道如何實現以下項目使用Ajax來渲染HTML表格

其實我有一個PHP代碼,這使得一臺

<table id = "oldata" class ="table table-bordered"> 

    <thead> 
      <tr class ="success"> 
        <th class="text-center">Stage</th> 
        <th class="text-center">REQUEST</th> 
        <th class="text-center">REPLY</th> 
      </tr> 
     </thead> 

    <tbody> 
<?php 

    foreach($allinfool as $infool){ 
     print("<tr>"); 
     print("<td>{$infool["Stage"]}</td>"); 
     print("<td class='text-left'>" .nl2br($infool["comment"])."</td>"); 
     print("<td class='text-left'>" .nl2br($infool["resultcom"]). "</td>"); 
     print("</tr>"); 
    } 

?> 
    </tbody> 

</table> 

到目前爲止好,但是我想根據用戶的操作構建許多像上面這樣的表格。 我的意思是他將有一個項目列表(如選擇1,選擇2,選擇3 ...),然後通過點擊它將呈現,而無需重新加載上面的HTML頁面(基於新的allinfool數組)。

我的觀點是我想通過Ajax做到這一點。到目前爲止,我可以管理Ajax,但不能渲染html的內容。 我可以設法返回一個數字或一個文本,但在這種情況下,它更復雜,因爲HTML與PHP混合。 你能幫我弄清楚如何實現這個Ajax技術嗎?

回答

4

把你的代碼文件中像table.php然後從index.php使用jQuery來調用它,使表:

HTML:

<button id="rendertable">Render new table</button> 
<div id="render"></div> 

JS:

$(document).ready(function() { 

    $('#rendertable').click(function() { 
     $.ajax({ 
      url: "table.php", 
      success: function (response) { 
       $('#render').append(response); 
      } 
     }); 
    }); 

}); 

每次你會點擊按鈕它會渲染一個新表格,附加到render元素

+0

謝謝你的回覆,我應該在table.php裏面做一些特殊的事情來吐出hmtl嗎?你能告訴我嗎? – Oeiloff

+0

不,你不需要任何東西(來渲染表格),如果你從瀏覽器中調用table.php,你會看到你將渲染的東西:表格。 –

+0

我試過了,這正是我的預期。謝謝 - – Oeiloff

0
you need to do this code in you main file from where you want to call table.php file - 
and pass the array variable into your $allinfool variable in table.php like- 
$allinfool = array(); 
$allinfool = $_POST['variable_value']; 
You have done. 

//this code is for your index.php file or any other file from where you want to call table.php 
<?php 
    $arr = array(
     array("Stage" => "Stage_value1", "comment" => "comment_value1", "resultcom" => "resultcom_value1"), 
     array("Stage" => "Stage_value2", "comment" => "comment_value2", "resultcom" => "resultcom_value2"), 
     array("Stage" => "Stage_value3", "comment" => "comment_value3", "resultcom" => "resultcom_value3") 
    ); 
    $arr = json_encode($arr); 
    ?> 
    <button id="button">Click Me</button> 
    <div id="success"></div> 
    <div id="error"></div> 
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
    <script> 
    $("document").ready(function(){ 
     $("button#button").on("click", function(){ 
     $("#success").load("table.php", { 'variable_value' : <?php echo $arr ?> }, function(response, status, xhr) { 
      if (status == "error") { 
      var msg = "Sorry but there was an error: "; 
      $("#error").html(msg + xhr.status + " " + xhr.statusText); 
      } 
     }); 
     }); 
    }); 
    </script>