以这种格式在 PHP 中创建一个关联的 javascript 对象字面量数组:
<?php
echo "
<!-- this script goes in your <head> -->\n
<script>\n
var db_array = [";
$result = mysqli_query($link, "SELECT * FROM db_scripts");
$first = TRUE; // remove trailing comma from array
while ($data = mysqli_fetch_object($result)) {
if ($first === TRUE) $first = FALSE;
else echo ',';
echo "
{
id: '$data->script_id',
name: '$data->script_name'
message: '$data->script_message'
}";
}
echo "];\n
</script>";
?>
问题是,如果您的消息与 id 不在同一行,那么您需要JOIN
在查询中使用。这部分背后的想法是您只查询数据库一次。您不希望客户端在每次切换下拉菜单中的选项时都查询数据库。这里的例外是如果您有兆字节以上的消息。在这种情况下,请考虑实施缓存措施。
继续......一旦你构建了数组,你可以<option>
通过迭代数组来构建你的 s ,如下所示:
<?php
echo "
<form action=\"$PHP_SELF\" method=\"post\">\n
<select id=\"conditions\" name=\"conditions\">\n
<option value=\"Select\" selected>Select a Message</option>\n
<script>\n
for (var i = 0; i < db_array.length; i++) {\n
document.write('<option value=\"'+db_array[i].id+'\">'+db_array[i].name+'</option>');\n
}\n
</script>\n
</select>\n
<!-- notice the id attribute I added -->\n
<br><textarea id=\"message\" name=\"message\" style=\"width:300px; height:130px\" data-maxsize=\"160\" data-output=\"status1\" wrap=\"virtual\" maxlength=\"160\"></textarea><br />\n";
?>
...然后有一个脚本可以访问这些动态创建的 DOM 元素(例如在<body>
标签的末尾)
<script>
// returns the db_array index of the object id supplied
function returnIndex (id) {
for (var i = 0; i < db_array.length; i++) {
if (db_array[i].id === id) return i;
}
return -1; // returns index of -1 if id is not found
}
// changes the <textarea> message. notice the id I added to the messages <textarea> above
function changeMessage (id) {
// remember to handle the case of an id not being found within db_array (where returnIndex returns -1)
document.getElementById('message').innerHTML = db_array[returnIndex(id)].message;
}
// on the event that we switch options, do this event. realize that you'll have to run the changeMessage function once the page loads if you want the first option's message to show
document.getElementById('conditions').onchange = function() {
changeMessage(this.selectedIndex);
}
</script>