使用PHP文件中的JSON填充SELECT(AJAX REQUEST)

时间:2013-07-23 22:17:49

标签: ajax json select fill

我已经花了好几个小时(时间不多了才能完成这项工作)试图弄清楚如何使用AJAX从之前选择的状态填充城市选区

PHP文件如下所示:

include_once("../models/class-Zone.php");

$state= $_GET["st"];

$cities= Zone::getCities($state);

echo json_encode($cities);

当我使用ajax ALERT结果时:

$.post(
        '../ajax/getcities.php?st='+stateid,
        function(data) {
            alert(data);
        }
    );
//I GET THIS:

[{"id":"08078","titulo":"BARANOA"},
{"id":"08001","titulo":"BARRANQUILLA"},
{"id":"08137","titulo":"CAMPO DE LA CRUZ"},
{"id":"08141","titulo":"CANDELARIA"},
{"id":"08296","titulo":"GALAPA"},
{"id":"08132","titulo":"JUAN DE ACOSTA"},
{"id":"08421","titulo":"LURUACO"}]

我还没有找到一种方法来迭代并用这些数据填充SELECT。选择应该如下所示

<select name="city" id="city">
    <option value="ID FROM THE JSON">TITULO FROM THE JSON ARRAY</option>
    ... AND FOR THE REST OF THE RESULTS
</select>

事先谢谢你!我很困惑。

2 个答案:

答案 0 :(得分:1)

首先解码JSON,然后将HTML添加到每个城市的选择中。

function(data) {
    var cities = JSON.parse(data);
    for(var c in cities) {
        document.getElementById('city').innerHTML += '<option value="' + cities[c].id +'">' + cities[c].titulo + '</option>';
    }
}

答案 1 :(得分:0)

看来你正在使用jQuery,所以我认为你可以轻松地在成功回调中迭代JSON

function(data){
    var st=""
    for(i in data){
        st+="<option id='"+data[i].id+"'>"+data[i].titulo+"</option>"
    }
    //here st contains all the options
    // you just have to append it in your select's html
    // I don't know your DOM structure, so if you didn't have anything 
    // you can add the select, then display it
    $("thePlaceWhereYouWantIt").html("<select>"+st+"</select>")
    }

它应该可以工作,但这取决于你的实际HTML

祝你好运