0

我正在尝试从 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>
4

3 回答 3

0

写你php codeseparate file类似balance.php

ajax code替换index.phpbalance.php喜欢

 $.ajax({
     url: 'balance.php',

否则die()echolike之后使用

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'];
        die();
    break;
}

使用die($balance_object['balance']);代替

echo $balance_object['balance'];die();

于 2013-10-09T06:43:57.263 回答
0

在此代码之后添加 exit(); 内部开关 - 案例:getbalance

echo $balance_object['balance'];
exit();
于 2013-10-09T06:46:50.127 回答
0

请加

dataType:"text"

作为 ajax 调用的参数。如果不指定 dataType,AJAX 将不知道调用期望返回某些内容。dataType 指的是返回的类型。整数 0 可以表示为文本“0”。

如果它不起作用,您可以尝试从 AJAX 调用参数中删除“成功”键。然后,改为这样做

$.ajax({...parameters...}).done(function(response){...to be done after ajax call...});

您可能还需要检查操作。您可以改为调用 getbalance.php 并编写返回 0 的函数。

于 2013-10-09T06:52:42.553 回答