如何使用php从mysql检索数据并在javascript上显示?

我正在尝试使用 php 和 javascript 创建实时更新。例如,如果用户添加了一个新客户端,则应使用 javascript 将行数反映在 HTML 的元素上。有人可以教我怎么做吗?我在下面有这个代码,并试图检索它,但它没有值。


PHP:


<?php

    include("pConfig.php");

    session_start();

    $cntPending = 0;

    $sql = "SELECT * FROM ci_account_info Where Status = 0";

    $result = mysqli_query($db,$sql);

    if (!$result) {

        printf("Error: %s\n", mysqli_error($db));

        exit();

    }

    $cntPending = mysqli_num_rows($result);

?>

爪哇脚本:


function getTimeSheetValue() {

        $.ajax({

            type: 'POST',

            url: '../back_php_Code/pCntPending.php',

            dataType: 'json',

            data: '',

            contentType: 'application/json; charset=utf-8',

            success: function (response) {

                                var cells = eval("(" + response.d + ")");

            document.getElementById("lblPending").innerHTML = cell[0].value;

            },

       });    

}

HTML:


<h4 id="lblPending" class="m-b-0">0</h4>


阿晨1998
浏览 118回答 1
1回答

潇潇雨雨

当查询成功时,您必须在 PHP 中添加 echo 行,然后 php 可以将消息发送回 ajax,因此更改您的 PHP 代码:&nbsp;<?php&nbsp; &nbsp; &nbsp;include("pConfig.php");&nbsp; &nbsp; &nbsp;session_start();&nbsp; &nbsp; &nbsp;$cntPending = 0;&nbsp; &nbsp; &nbsp;$sql = "SELECT * FROM ci_account_info Where Status = 0";&nbsp; &nbsp; &nbsp;$result = mysqli_query($db,$sql);&nbsp; &nbsp; &nbsp;if (!$result)&nbsp;&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;printf("Error: %s\n", mysqli_error($db));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;exit();&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;else&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$cntPending = mysqli_num_rows($result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;echo $cntPending;&nbsp; &nbsp; &nbsp;}&nbsp;?>而你的javascript需要稍微改变一下:function getTimeSheetValue(user, pass) {&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; url: '../back_php_Code/pCntPending.php',&nbsp; &nbsp; &nbsp; &nbsp; dataType: 'text',&nbsp; &nbsp; &nbsp; &nbsp; contentType: 'application/json; charset=utf-8',&nbsp; &nbsp; &nbsp; &nbsp; success: function (response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cell = response;&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("lblPending").innerHTML = cell;&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp;});&nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP