我有一个使用基本MVC结构的小型网站。 我有一些代码将两个值插入数据库,插入工作正常没有任何问题,但是,如果我想看到新数据我通常必须刷新页面或导航到另一个页面,然后返回。我知道我需要使用JQuery / Ajax来完成这项工作,但是我真的不明白如何使用PHP函数。
有问题的代码如下:
PHP功能:
<?php
session_start();
require_once('../Config/config.php');
class Readings
{
public $dbconn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->dbconn = $db;
}
public function enterElecReadings($eUsage)
{
try
{
$estmt = $this->dbconn->prepare("
INSERT INTO elec_readings
(ElecUsage, DateAdded, AccountNumber)
VALUES
(:eUsage, NOW(), :accNum)");
$estmt->bindparam(":eUsage", $eUsage);
$estmt->bindparam(":accNum", $_SESSION['user_session']);
$estmt->execute();
return $estmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function getElecReadings(){
try {
$stmt = $this->dbconn->prepare("SELECT ElecUsage, DateAdded FROM elec_readings WHERE AccountNumber = '" . $_SESSION['user_session'] . "'");
$stmt->execute();
return $stmt;
} catch (Exception $e) {
}
}
}
?>
用户将看到的页面:
if(isset($_POST['btn-submitElecUsage']))
{
$eUsage = strip_tags($_POST['txtElecUsage']);
try {
if($newReading->enterElecReadings($eUsage)){
$elecNotif[] = "Reading successfully entered.";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
<div class="elecUsage">
<form id="elecRead" method="POST">
<h2>Electricity Usage</h2>
<?php
if(isset($elecError))
{
foreach($elecError as $elecError)
{
?>
<div class="alert alert-danger">
<?php echo $elecError; ?>
</div>
<?php
}
}
if(isset($elecNotif))
{
foreach($elecNotif as $elecNotif)
{
?>
<div class="alert alert-danger">
<?php echo $elecNotif; ?>
</div>
<?php
}
}
?>
Please enter your latest electricity meter reading:
<br>
<input type="text" name="txtElecUsage" required/>
<br>
<input type="submit" name="btn-submitElecUsage" value="Submit"/>
</form>
<br>
Your previous Electricity meter readings:
<br>
<div id="previousElecReadings">
<br>
<table class="tableElec" >
<thead>
<tr>
<th>Usage</th>
<th>Date Added</th>
</tr>
</thead>
<?php
foreach ($elec_readings as $elec_reading): ?>
<tbody>
<tr>
<td><?php echo $elec_reading['ElecUsage']; ?></td>
<td><?php echo $elec_reading['DateAdded']; ?></td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
</div>
</div>
控制器类:
<?php
require_once('../Model/readingsModel.php');
require_once('../Tool/DrawTool.php');
$newReading = new Readings();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/meterReadings.php', array('elec_readings' => $newReading->getElecReadings()),
array('gas_readings' => $newReading->getGasReadings()));
echo $renderedView;
?>
正如我上面所说的那样。插入工作正常。但我想看到数据立即出现而不必刷新。
有什么想法吗?
由于
答案 0 :(得分:1)
所有它真的像浏览器一样,在后台点击该页面。您可以选择是否回拨数据,但就好像您的浏览器已转到该页面一样,因此您将其视为任何其他页面。这只是一个剪切和粘贴,但这可能很接近:
index.php(无论你的初始页面是什么):
<!-- use the id to target the form -->
<form id="elecRead" method="POST">
<h2>Electricity Usage</h2>
<!-- You just have an empty container where your ajax will return -->
<div id="errors"></div>
Please enter your latest electricity meter reading:
<br>
<input type="text" name="txtElecUsage" required/>
<br>
<input type="submit" name="btn-submitElecUsage" value="Submit"/>
</form>
...etc...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
// When page is done loading
$(document).ready(function(){
// When this particular form is submitted
$('#elecRead').submit(function(e){
// Stop normal refresh of page
e.preventDefault();
// Use ajax
$.ajax({
// Send via post
type: 'post',
// This is your page that will process the update
// and return the errors/success messages
url: "page2.php",
// This is what compiles the form data
data: $(this).serialize(),
// This is what the ajax will do if successfully executed
success: function(response){
// It will write the html from page2.php into an
// element with the id of "errors", in our case
// it's a div
$('#errors').html(response);
},
// If the ajax is a failure, this will pop up in the console.
error: function(response){
console.log(response);
}
});
});
});
</script>
page2.php(处理页面):
<?php
// Page two just contains the processing of the update
// so include everything that you need to do that
session_start();
require_once(__DIR__.'/../Config/config.php');
require_once(__DIR__.'/../Model/readingsModel.php');
// Check for the post
if(isset($_POST['btn-submitElecUsage'])){
// Create the instance of your class that does the update and error
// handling/rendering
$newReading = new Readings();
$eUsage = strip_tags($_POST['txtElecUsage']);
try {
if($newReading->enterElecReadings($eUsage)){
$elecNotif[] = "Reading successfully entered.";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
// I am just using a buffer, but you don't need it
ob_start();
// I presume this variable is on an included page, I don't see it
// anywhere but if you include the same stuff as your initial page,
// it should show up here fine
if(isset($elecError)){
foreach($elecError as $elecError){
?>
<div class="alert alert-danger">
<?php echo $elecError; ?>
</div>
<?php
}
}
if(isset($elecNotif)){
foreach($elecNotif as $elecNotif){
?>
<div class="alert alert-danger">
<?php echo $elecNotif; ?>
</div>
<?php
}
}
$data = ob_get_contents();
ob_end_clean();
// Just print the contents of the page and your ajax on page 1
// will take this content and place it in the <div id="errors"><div>
die($data);
答案 1 :(得分:0)
使用纯PHP,您无法刷新页面。所以使用AJAX!
这是一个小例子
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="name"/>
<input type="submit" id="submit" value="Send"><br/><br/>
<div id="response"><div>
<script>
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var value = $('#name').val();
if (value != ''){
$.ajax({
type: "POST",
url: "your_process_file.php",
data: { name:value },
success: function(data){
$('#response').html(data);
},
fail: function(data){
$('#response').html('There is an error!');
}
});
}
});
});
</script>
</body>
</html>
your_process_file.php可能如下所示:
$name = $_POST['name'];
$stmt = $db->prepare('SELECT * FROM tblName WHERE name=?');
$stmt->execute([$name]);
while ($row = $stmt->fetch()){
echo $row['col1'],' ',$row['col2'],' ',$row['colN'];
}
假设您在db表中有一些数据:
id name address
1 abc address1
2 def address2
然后,当您在文本框中写入时,fe,abc表格中的整行将在<div id="response"></div>
内返回而不刷新页面。
OBS:我认为代码中可能存在一些错误,因为我没有对其进行测试。