我应该如何使用html,jQuery构建一个控制数组


How should I build a control array using html, jQuery

我对html-php-jquery-ajax组合只有基本知识,但我在VB工作了很长时间。我可以用VB的术语最好地描述我试图做的事情,但我需要在已经使用jquery、ajax和php接口的html/php页面中做这件事。

我正在查询数据库并返回id&描述我想动态地构建一个控制数组来表示返回的数据。

此函数调用从按钮onclick事件读取的数据库。。。

    <script type="text/javascript">
    function loadio(){
        var request = $.ajax({
            url: "/db/loadio.php", type: "POST", datatype: "html"
        }); //request   
        request.done(function(result) { 
            $('#status').html("Result: " + result );
        });  //request.done
        request.fail(function(jqXHR, textStatus) {
            $('#status').html("Request failed: " + textStatus + " " + jqXHR.status );
            }); //request.fail
    }; //loadio
</script>

它调用这个php文件并从中返回数据。。。

<?php
    $con = new mysqli('localhost', 'user', 'password', 'dbtable');
        $stmt = $con->prepare('select id, description from iotable where iotype = 1');  
        $stmt->execute();
        $stmt->bind_result($id, $description);
        while ($stmt->fetch()){
            echo $id, $description, "<br/>";
        }
        $stmt->close();
    $con->close();
?>

所以我想做的是:构建一个表示返回的$描述的标签数组,以及构建一个相应的按钮数组,以某种方式分配#id,这样当单击时,它们可以将#id用作一个变量,该变量可以传递给一个公共函数(例如警报("按钮"+#id+"被点击");)。

如果我必须在.NET中这样做,我会创建一个包含控件和事件的类,并根据需要创建该类的新实例,将所有必需的变量存储在该实例中。

所以我的问题是:我应该如何使用html、php、jQuery和ajax来实现这一点?我可以创建动态控制阵列吗?我需要考虑一种完全不同的方法吗?

提前谢谢。

您要做的是用php填充数组,然后以JSON格式发回:

<?php
    header('Content-type: application/json'); //we tell the browser that we are going to send json
    $con = new mysqli('localhost', 'user', 'password', 'dbtable');
    $stmt = $con->prepare('select id, description from iotable where iotype = 1');  
    $stmt->execute();
    $stmt->bind_result($id, $description);
    $results = array(); //array declaration
    while ($stmt->fetch()){
        $results[$id] = $description; //associative array : key = id, value = description
    }
    $stmt->close();
    $con->close();
    echo json_encode($results); //we send (ie print) json-encoded array $results
    exit(); //not mandatory, just to precise that the script has to stop here
?>

然后您将收到javascript中的json数组,您可以对其进行解码并在其上循环,例如:

request.done(function(result) { 
    var results =  $.parseJSON(result);
    $.each(results, function(){
        //create here your buttons
    });
});