我应该如何使用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
});
});
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 根据id将json数组组合为一个json数组
- JavaScript数组包含一个值
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- jQuery$.inArray()总是返回-1和一个对象数组
- 在数组中的一个元素上设置多个值
- javascript处理一个对象数组以获得一个新的对象数组
- 作为一个二维数组,从ajax接收
- 你能用来自数组的属性名称生成一个对象吗
- 多维关联数组的最后一个索引
- 如何创建一个方法来验证数组的范围
- 循环以检查数组中的最后一个图像
- 在Javascript中将一个值和字符串数组转换为if语句
- 算法:从数组(javascript/angular)中按当前日期获取上一个和下一个事件
- 如何将一个对象添加到每个对象数组中
- 如何创建一个谷歌地图地理坐标数组
- 如何从另一个带下划线的数组中筛选带元素的数组
- 如何在PHP数组中加载下一个youtube
- 查找对象数组是否包含其中一个标记的最快方法
- 如何使用Javascript和Ajax传递一个HTML选择标签到PHP $_POST与一个(数组)var当名称属性是一个