我正在尝试从 getbalance 操作中选择返回的值,但它显示的是整个站点的 HTML。我怎样才能让它只显示 POST 请求的结果,在这种情况下为 0?代码如下。
<?php
$dbc = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
session_start();
//Create user if there is no session for the user.
if(!isset($_SESSION['user_id'])) {
$random = rand(10000, 100000);
$create = $dbc->prepare('INSERT INTO users(user_id, balance, time, deposit) VALUES (?, ?, ?, ?)');
$create->execute(array($random, 0, time(), 0));
$_SESSION['user_id'] = $random;
}
//All actions posted by jQuery (Method & Controller).
switch($_POST['action']) {
case 'getbalance':
$balance = $dbc->prepare('SELECT balance FROM users WHERE user_id = ?');
$balance->execute(array($_SESSION['user_id']));
$balance_object = $balance->fetch();
echo $balance_object['balance'];
break;
}
?>
<html>
<head>
<title>Testing</title>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
var update_user_balance = setInterval(function() {
$.ajax({
url: 'index.php',
type: 'POST',
data: { action: 'getbalance' },
success: function(update_user_balance) {
$('#balance').html(update_user_balance);
}
});
}, 1000);
</script>
</head>
<body>
<div id='welcome'>
<h2>Welcome to Testing</h2>
</div>
<div id='properties'>
<p>Your balance is <span id='balance'></span></p>
<p><a id='deposit'>Click here</a> to deposit.</p>
<p><a id='withdraw'>Click here</a> to withdraw.</p>
</div>
</body>
</html>