Ajax函数没有返回任何输出

时间:2017-03-18 10:59:51

标签: php jquery ajax mysqli

我正在使用这个ajax函数通过ajax获取两个下拉列表的选项,但它没有返回任何输出。 嗨,这是我的ajax功能:

 <script>
$('#department').on('change',function(){
    var department = $(this).val();
    var course = $('#course').val();
    if(department){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            dataType: 'json',
            cache: false,
            data:{department: department, course: course },
            success: function(data){
                $('#head_name').html(data.head_name);
                $('#email').html(data.email);
            }
        }); 
    }else{
        $('#head_name').html('<option value="">Select Department first</option>'); 
        $('#email').html('<option value="">Select Department first</option>'); 
    }
});
</script>

这是我的查询代码:

if(isset($_POST["department"]) && isset($_POST["course"])){
    //Get all courses data

    $query = $db->query("SELECT head_name, email FROM head WHERE course = '".$_POST['course']."' AND department = '".$_POST['department']."' ");

    //Count total number of rows
    $rowCount = $query->num_rows;

    //Display result list
    if($rowCount > 0){
        while($row = $query->fetch_assoc()){

            $temp = array('head_name' => '<option value="'.$row['head_name'].'">'.$row['head_name'].'</option>', 'email' => '<option value="'.$row['email'].'">'.$row['email'].'</option>' );
            echo json_encode($temp);
        }
    }else{
        $temp = array('head_name' => '<option value="">Not avaialble </option>', 'email' => '<option value="">Not avaialble </option>' );
        echo json_encode($temp);
    }
}

但是我没有从中得到输出结果,我做错了什么?

3 个答案:

答案 0 :(得分:1)

您的Ajax调用需要JSON(dataType: 'json'),但您不会通过PHP输出返回JSON,因为默认内容类型为text/html而不是application/json。在{J}输出Content-Type之前添加适当的echo标头。

header('Content-Type: application/json');
echo json_encode(array('something' => 'else'));

答案 1 :(得分:0)

您回显数组,因此您应该按索引访问数据元素作为数组。

例如,对于第一个元素

       success: function(data){
            $('#head_name').html(data[0].head_name);
            $('#email').html(data[0].email);
        }

最终尝试jsonParse数据

       success: function(data){
             jsonData = JSON.parse(data);
            $('#head_name').jsonData(data[0].head_name);
            $('#email').jsonData(data[0].email);
        }

在您应该使用数组存储值

的时候
        while($row = $query->fetch_assoc()){

        $temp[] = array('head_name' => '<option value="'.$row['head_name'].'">'.$row['head_name'].'</option>', 'email' => '<option value="'.$row['email'].'">'.$row['email'].'</option>' );
        echo json_encode($temp);
    }

答案 2 :(得分:0)

我刚刚更改了变量名称,我的功能开始工作,不知道为什么会这样:

data:{ department: department, courseid: course},