开发者

Populate select list from JSON

I've been looking around for a solution to what appears to be a simple problem, but am unable to find the solution...any guidance would be appreciated.

I am attempting to build a select box using JSON object retrieved from a PHP script. The PHP script (versions.php) is running a query against a database table; code is as follows:

$posts = array();
if(mssql_num_rows($result)) {
  while($post = mssql_fetch_assoc($result)) {
    $posts[] = $post;
  }
}
header('Content-type: application/json');
echo json_encode($posts);

...and returns the following json structure:

[{"version":"3.3.0"},{"version":"1.5.0"}]

The PHP file is being called from a central JS 开发者_运维百科file, which is structured as follows:

jQuery(function($){
    $.getJSON('versions.php', function(data) {
        var select = $('#release-list');
        $.each(data, function(key, val){
            var option = $('<option/>');
            option.attr('value', val)
                  .html(data)
                  .appendTo(select);
        });
    });
});

Looking at firebug, I see lists of objects, but not the values in the array. I guess this is related to the code in the javascript file above - just not sure how to access the values from the json object.

Thanks in advance.


You're almost there. Based on your JSON structure, It should look something like this:

jQuery(function($){
    $.getJSON('versions.php', function(data) {
        var select = $('#release-list');
        $.each(data, function(key, val){
            $('<option/>').attr('value', val.version)
                  .html('version ' + val.version)
                  .appendTo(select);
        });
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜