2015-08-28 135 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>