我試圖從getbalance操作中選擇返回的值,除了它顯示整個網站的HTML。我怎麼能只顯示在這種情況下是0的POST請求的結果?代碼如下。jQuery .html()只選擇特定內容?
<?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>
有沒有其他的方式做到這一點,而不必做出單獨的文件..? –
它更好地爲'ajax'製作'獨立文件',否則你可以'在相同頁面中'回顯你的數據'後使用die''看到我的'更新的答案' –
完美,謝謝。 –