如何使用json填充选择框?

时间:2017-06-17 19:06:10

标签: php jquery html json

我尝试使用json和PHP填充HTML页面中的选择框,但是当我点击选择框时,它只返回一个空白选项。什么是错的?

HTML code:

Choose a problem:
<select name="notification" id="notification" class="form-control">
   <option value="00">Select...</option>
</select>

PHP代码:

header('Access-Control-Allow-Origin: *');
include 'dbconfig.php';
try{
    $results = $DB_con->prepare("SELECT idproblema, tipoproblema FROM problema ORDER BY idproblema");
    $results->execute();
    $res = $results->fetchAll(PDO::FETCH_ASSOC);
    $hold = array();

    foreach($res as $reg){
$hold[] = array('idproblema' => $reg['idproblema'], 'tipoproblema' =>$reg['tipoproblema']);
    }
} 
catch (Exception $e) {
    echo "Data could not be retrieved from the database.";
    exit();
}
echo json_encode($hold);

Jquery代码:

$(document).ready(function(){
jQuery.support.cors = true;
$('#notification').click(function(){
    $.ajax({
        url : 'url.php',
        type : 'GET',
        data : "json",
        crossDomain: true,
        success: function (data) {
        if (data.length > 0) {
            $.each(data, function (index, value) {
                $('#notification').append('<option value="' + value.idproblema+ '">' + value.tipoproblema + '</option>');
            });
        }
        else {
            var newOption= $('<option value=""></option>');
            $('#notification').append(newOption);
        }
    }
});
});
})

...............................................

1 个答案:

答案 0 :(得分:0)

你需要在php之前添加echo .... 标题(&#39;内容类型:application / json&#39;); .... 由于jQuery $ .ajax设置为接受json数据 - 此时只返回文本