JSON成功不会触发

时间:2019-06-10 16:47:33

标签: php json ajax

我的JSON有效负载有问题。成功功能不会触发。

在此先感谢您能提供的任何帮助。 捷豹路虎

我在控制台中获取了值,所以我知道查询可以正常运行,但是它不在键/值对中,它仅回显“ VALUE”,并且不会触发成功。

//JS file ***UPDATED***

    $(document).ready(function(){
// code to get all records from table via select box
        $("#school").change(function() {
            var id = $(this).find(":selected").val();
            var dataString = 'school='+ id;
            $.ajax({
                url: 'cif_submit.php',
                dataType: "json",
                data: dataString,
                cache: false,
                success: function(data) {
                    if(data) {
                        alert(data);
                    }
                }
            });
        })
    });
//Here is the php  ***UPDATED***

if($_REQUEST['school']) {

$stmt = $conn->prepare("SELECT streetname FROM schoolinfo WHERE fullschoolname = :schoolname");
$stmt->execute (array(':schoolname' =>$_REQUEST['school']));

while($mydata = $stmt->fetch()) {   

    echo json_encode($mydata);  
} }
}

The JSON RESPONSE is:
{"streetname":"Colbeck Road, PO Bag 7200","0":"Colbeck Road, PO Bag 7200"}

2 个答案:

答案 0 :(得分:0)

我认为将学校数据更改为数据将解决此问题。

答案 1 :(得分:0)

别忘了当您使输入失去焦点时会调用change()事件。 https://api.jquery.com/change/

尝试使用此代码并完美运行。

JS

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<input id="school" type="text">
<script>
    $(document).ready(function(){
// code to get all records from table via select box
        $("#school").change(function() {
            var id = $(this).find(":selected").val();
            var dataString = 'school='+ id;
            $.ajax({
                url: 'a.php',
                dataType: "json",
                data: dataString,
                cache: false,
                success: function(schooldata) {
                    if(schooldata) {
                        alert('success');
//$("#streetname").text(schooldata.streetname);  TRIED THIS NO JOY
//$("#streetname").hide(); TRIED THIS NO JOY
                    }
                }
            });
        })
    });
</script>
</body>
</html>

PHP

if($_REQUEST['school']) {
    $datas = array();
    $datas[] = array('streetname' => 'test');
    foreach ($datas as $data) {
        $data = $data['streetname'];
        //$streetname = trim(json_encode($data), '"');
        //echo json_encode($data);
        echo json_encode($data, true);
    }
}

Alert