我創建了一個簡單的表單,並使用Datatables jQuery插件在其中顯示一些數據。數據由php腳本(process.php)填充,以JSON格式返回正確的結果。在表單中,有一個按鈕將文本框的值發送到process.php。 問題是,當點擊按鈕時,我無法使用process.php腳本收到的新數據更新/更改數據表。單擊按鈕時更新datatables(jQuery)
形式的代碼:
<form name="myform" id="myform" action="" method="POST">
<label for="id">Enter an id:</label>
<input type="text" name="txtId" id="txtId" value=""/>
<input type="button" id="btnSubmit" name="btnSubmit" value="Search">
</form>
<div id="results">
<table class="display" id="example">
<thead>
<tr>
<th>id</th>
<th>Surname</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<!-- data goes here -->
</tbody>
</table>
</div>
要創建數據表,我用下面的jQuery代碼:
$(document).ready(function() {
var oTable = $('#example').dataTable({
"sPaginationType": "full_numbers",
"iDisplayLength": 10,
//"bServerSide": true,
"sAjaxSource": "process.php"
});
$("#btnSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php",
data: 'txtId=' + $("txtId").val(),
success: function(result) {
oTable.fnReloadAjax();
oTable.fnDraw();
}
});
});
});
process.php腳本(正常工作)是:
<?php
$result="";
if (empty($_REQUEST["txtId"])) {
$result = '{"aaData":[["1","Surname1","Name1"]]}';
}
else {
$result = '{"aaData":[["2","Surname2","Name2"]]}';
}
print $result;
?>
** **從未使用字符串函數創建JSON。 PHP有'json_encode()'。在你的情況,你會使用'echo json_encode(array('aaData'=> array(array('1','Surname1','Name1')));' – ThiefMaster 2012-04-15 09:38:11
是的,我知道json_encode()函數。上面的process.php腳本是爲了簡單起見而編寫的。無論如何,感謝ThiefMaster! – dimmat 2012-04-15 11:43:24