带有[echo json_encode']的消息(数组)php到ajax不显示数据

我正在尝试将一组数据从 PHP 发送到 ajax。我正在使用 echo json_encode 来做到这一点。当我这样做时,我尝试“console.log(data)”来查看响应数据,但它没有显示任何内容。我怎样才能让它显示数据?我真的不知道我在这里错过了什么。我有这个脚本:


var scard = $('#cardid').val();

$.ajax({

    type: 'GET',

    url: 'cardapi.php?scard=' + scard,

    success: function (data) {

        console.log($.parseJSON(data));

        console.log(data);

    }

});

这是我的 cardapi.php 代码


if(isset($_GET["scard"])){

    $scard = $_GET["scard"];

    $data = array();


    $sql = "SELECT * FROM training_record WHERE cardref_no='$scard'";

    $q = sqlsrv_query($conn, $sql);


    while($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)){

        array_push($data,[

            "employee_no" => $rw["employee_no"],

            "dept_id" => $rw["dept_id"],

            "name_th" => $rw["name_th"],

            "surname_th" => $rw["surname_th"],

            "signed_status" => 1,

        ]);


    }


    echo json_encode($data);

}

所以我尝试遵循这个echo json_encode() not working via ajax call

它仍然没有显示任何东西。请告诉我为什么?


有只小跳蛙
浏览 112回答 1
1回答

BIG阳

您可以尝试以下方法:始终检查sqlsrv_query()执行结果。始终尝试使用参数化语句。函数sqlsrv_query()既做语句准备又做语句执行,可用于执行参数化查询。检查json_encode()调用的结果。修复输入错误(例如"signed_status" => 1,应该是"signed_status" => 1)。示例脚本,基于您的代码:<?phpif (isset($_GET["scard"])) {&nbsp; &nbsp; $scard = $_GET["scard"];&nbsp; &nbsp; $data = array();&nbsp; &nbsp; $sql = "SELECT * FROM training_record WHERE cardref_no = ?";&nbsp; &nbsp; $params = array($scard);&nbsp; &nbsp; $q = sqlsrv_query($conn, $sql, $params);&nbsp; &nbsp; if ($q === false) {&nbsp; &nbsp; &nbsp; &nbsp; echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);&nbsp; &nbsp; &nbsp; &nbsp; exit;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; while ($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)) {&nbsp; &nbsp; &nbsp; &nbsp; $data[] = array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "employee_no" => $rw["employee_no"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "dept_id" => $rw["dept_id"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name_th" => $rw["name_th"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "surname_th" => $rw["surname_th"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "signed_status" => 1&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp; $json = json_encode($data);&nbsp; &nbsp; if ($json === false) {&nbsp; &nbsp; &nbsp; &nbsp; echo json_last_error_msg();&nbsp; &nbsp; &nbsp; &nbsp; exit;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; echo $json;}?>
打开App,查看更多内容
随时随地看视频慕课网APP