这里是 PHP/MySQL 新手,我一直在尝试学习一些 Ajax。
我想将一些 JSON(一个数字,例如 12345
)返回到 $variable
和echo
该变量位于单个表格单元格中。 (可能有更好的方法来做到这一点,但我只想知道它是如何完成的 - 如果可能的话!)
到目前为止,我可以检索 JSON 数字并将其显示在 <div id="result"></div>
中使用下面的代码,所以我知道请求有效 - 我只是坚持传递变量部分。
我的回复(在 Chrome 中)如下所示;
到目前为止我的代码是;
chartAjax.php
<form method="post" id="search">
<input type="text" id="date" name="date">
<input type="submit" value="Submit">
</form>
<div id="result"></div> <!-- this successfully displays the figure on submit -->
<table id="datatable" class="table">
<tbody>
<tr>
<th>Data</th>
<td>{NEED TO echo the $result here}</td> <!-- stuck here -->
</tr>
</tbody>
</table>
monthConn.php
<?php
/* set header type to json */
header('Content-Type: application/json');
/* array to pass back data */
$data = array();
/* get date from form submit */
if (isset($_POST['date']) && !empty($_POST['date'])){$date = $_POST['date'];}
/* Create a prepared statement */
$stmt = $conn -> prepare("SELECT count(*) FROM transactions WHERE TimeStamp >= ?");
/* Bind parameters */
$stmt -> bind_param("s", $date);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($data);
/* fetch values */
$stmt->fetch();
/* close conn */
$stmt->close();
echo json_encode($data);
?>
我的JS(包含在上面的chartAjax.php页面中)
<script>
$(document).ready(function() {
$('#search').submit(function(event) {
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
ajaxRequest= $.ajax({
url: "monthConn.php",
type: "post",
data: values,
success: function(response, data) {
if(data == "success") {
$("#result").html(response); //add response to results div
}
},
});
});
});
</script>
如果代码/方法非常业余,我们深表歉意,欢迎任何帮助或建议!
最佳答案
试试这个
添加此(AS 计数)
$stmt = $conn -> prepare("SELECT count(*) AS count FROM transactions WHERE TimeStamp >= ?");
然后应用这个
//just incase you want to return more than 1 value in the future
return json_encode(array('count' => $data));
然后在你的
if(data == "success") {
var return_data = $.parseJSON(response);
$("#datatable").html(return_data['count']);
}
<table id="datatable" class="table">
<tbody>
<tr>
<th>Data</th>
<td id="response"></td>
</tr>
</tbody>
</table>
关于javascript - Ajax 和 PHP 将数据返回到表格单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115438/