Javascript jQuery.html()是否仅选择特定内容?

Javascript jQuery.html()是否仅选择特定内容?,javascript,jquery,html,Javascript,Jquery,Html,我试图从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($_SESS

我试图从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>
在单独的文件(如balance.php)中编写php代码

在ajax代码中,将index.php替换为balance.php

否则使用回显后的模具

或者使用die$balance_object['balance'];代替


echo$balance_对象['balance'];死亡

在此代码后添加退出;内部开关-外壳:getbalance

echo $balance_object['balance'];
exit();
请加上

dataType:"text"
作为ajax调用的参数。 如果不指定数据类型,AJAX将不知道调用需要返回什么。数据类型引用返回的类型。整数0可以表示为文本0

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

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

您可能还需要检查操作。您可以调用getbalance.php,然后在那里编写返回0的函数。

有没有其他方法可以在不需要创建单独文件的情况下执行此操作?最好为ajax创建单独的文件,否则您可以在同一页面中回显数据后使用die查看我的更新答案
dataType:"text"
$.ajax({...parameters...}).done(function(response){...to be done after ajax call...});