使用JSON数据动态填充下拉列表 [英] Populate dropdown dynamically using JSON data

查看:132
本文介绍了使用JSON数据动态填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下拉菜单中显示高尔夫球场的名称时遇到问题.我有一个PHP脚本,该脚本在运行时返回数据库中课程的名称.问题是,当我将其应用于index.html下拉页面并在浏览器中显示时,内容未显示该下拉列表.

I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is that when I apply this to my index.html dropdown page and display it in the browser, the content is not displaying the dropdown.

<?php


    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = '';

    $con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
    if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
    }   


    $sql = "SELECT name FROM courses";

    $result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));;

    $courses = array();

    while ($row = mysqli_fetch_array($result))
    {
        array_push($courses, $row["name"]);
    }

    echo json_encode($courses);

?>

上面的代码成功地从数据库生成了数据

The above code successfully generates the data from the database

$(document).ready(function () {
    $.getJSON("getCourseDD.php", success = function(data){
        var options = "";
        for(var i=0; i< data.length; i++){
            options += '<option value ="' + data[i] + '">' + '</option>';
        }
        $("#selectCourse").append(options);
    });
});

上面的代码没有将课程名称填充到下拉菜单中.

The above code is not populating the course names into the dropdown menu.

我的下拉菜单的ID为selectCourse.

The id of my dropdown menu is selectCourse.

<form> <select id="selectCourse" </select> </form>

非常感谢您提前提供帮助.

Thanks for any help in advance.

推荐答案

当前您还没有设置option的文本,请使用

Currently you are not setting text of option also, use

options += '<option value ="' + data[i] + '">' +  data[i]  + '</option>'

代替

options += '<option value ="' + data[i] + '">' + '</option>';

这篇关于使用JSON数据动态填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆