在另一个表中插入下拉列表中所选名称的ID,可以通过以下步骤实现:
下面是一个示例的代码片段,用于演示如何在另一个表中插入下拉列表中所选名称的ID:
<!-- HTML -->
<select id="dropdown">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
</select>
<button onclick="insertID()">Insert ID</button>
<script>
function insertID() {
var dropdown = document.getElementById("dropdown");
var selectedOption = dropdown.options[dropdown.selectedIndex].value;
// Send AJAX request to server
var xhr = new XMLHttpRequest();
xhr.open("POST", "/insert", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("ID inserted successfully");
}
};
xhr.send(JSON.stringify({ option: selectedOption }));
}
</script>
// Node.js (Express) server code
app.post("/insert", function(req, res) {
var selectedOption = req.body.option;
// Query options table to get ID
var query = "SELECT id FROM options WHERE name = ?";
db.query(query, [selectedOption], function(err, result) {
if (err) throw err;
var selectedID = result[0].id;
// Insert ID into target table
var insertQuery = "INSERT INTO target_table (option_id) VALUES (?)";
db.query(insertQuery, [selectedID], function(err, result) {
if (err) throw err;
res.sendStatus(200);
});
});
});
请注意,以上代码仅为示例,实际应用中需要根据具体的开发环境和需求进行适当的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云