Ajax填充下拉菜单只需点击两次


Ajax Populated Dropdown Taking Two Clicks

我的网页是我公司的内部DB移动工具。我有source和target两部分。

我有主机和端口的单选按钮,和数据库名称的下拉。设置主机和端口后,在下拉菜单上有一个点击事件捕获,它向php页面发送一个ajax请求,该页面查询该实例上的数据库并填充下拉选项(这是针对目标下拉菜单):

    $("#targetDrop").one("click",function() {
    ajaxTarget();
     });

function ajaxTarget() {
    $.ajax({
        url: './dbLookup.php',
        type: 'POST',
        dataType: "json",
        data: {
            host: $("#targetHost:checked").val(),
            port: $("#targetPort:checked").val()
        }
    })
        .done(function(result) {
            console.log("Setting Result");
            for (i=0; i<result.length; i++) {
                $("#targetDrop").append("<option name='"targetDB'" value='"" + result[i] + "'">" + result[i] + "</option>");
            }
        })
        .fail(errorFn)
        .always(function (data,textStatus,jqXHR){
            console.log("The request is complete!")
        });

我的问题是,您必须单击下拉菜单一次(没有显示),取消选择它,然后再次单击它以查看填充的值。这是有道理的,因为它需要点击来生成数据,所以我需要重新选择下拉菜单来查看新数据。

有没有办法让这一切发生在第一次点击?

谢谢!

还有一种更有效的方法:

$("#targetHost, #targetPort").change(function () {
    if ($.trim($("#targetHost:checked").val()) != "" && $.trim($("#targetPort:checked").val()) != "") {
        dbLookUp();
    }
});
function dbLookUp() {
    var data = {
            host: $("#targetHost:checked").val(),
            port: $("#targetPort:checked").val()
        }
    $.ajax({
        url: './dbLookup.php',
        type: 'POST',
        dataType: "json",
        data: data,
    }).done(function(response) {
        var opts = '<option value="">Choose Database...</option>';
        $.each(response, function(index, data) {
            opts += '<option name="targetDB" value="' + data + '">' + data + '</option>';
        });
        $("#targetDrop").html(opts);
    }).fail(function(response) {
        console.log(response);
    });
}
dbLookUp(); // Add this line if you have default selection for host and port
            // and you want to load the DB list as soon as the page loads up.

这样你就不必点击下拉菜单来加载它了…只要您选择主机和端口,它就会加载doropdown。您甚至可以在第一页加载时加载db列表。