javascript - 我应该如何使用 html、jQuery 构建一个控件数组

标签 javascript php jquery ajax

我对 html-php-jquery-ajax 组合只有基本的了解,但我在 VB 上工作了很长时间。我可以用 VB 术语最好地描述我尝试做的事情,但我需要在已经使用 jQuery、ajax 和 php 接口(interface)的 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();
?>

所以我想做的是: 构建一个代表返回的 $description 的标签数组,以及 构建相应的按钮数组,以某种方式分配 #id,以便单击时可以使用 #id 作为可以传递给常用函数的变量 (例如alert(“按钮”+#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
    });
});

关于javascript - 我应该如何使用 html、jQuery 构建一个控件数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229310/

相关文章:

javascript - 单击单选按钮时的 JQuery Slidedown() SlideUp()

javascript - 如何将Json数据转换为EXTJS中的变量

php - DOMDocument::loadHTML():作为输入提供的空字符串

javascript - ionic 点击事件触发两次

php - 网络监控

php pdo使用函数插入数据

php - 我怎样才能获得这种格式的二维数组?

javascript - Jquery 移动 CDN 替代方案

javascript - 文件上传/预览,无法更改图像尺寸

javascript - 使用 JS 或 jQuery 替换部分 URL