获取网页下拉菜单option的值,点击提交按钮后,写入MySQL数据表的type列,并弹出alert窗口显示该type值,PHP代码
时间: 2023-12-01 20:03:38 浏览: 55
php 获取select下拉列表框的值
以下是一个简单的示例代码,其中包含获取下拉菜单选项值、将其写入MySQL数据表并弹出alert窗口显示值的PHP代码。
HTML代码:
```html
<form id="myForm" method="post">
<select id="type" name="type">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<input type="button" value="Submit" onclick="submitForm()">
</form>
```
JavaScript代码:
```javascript
function submitForm() {
var type = document.getElementById("type").value; // 获取选项值
var xhr = new XMLHttpRequest();
xhr.open("POST", "save.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText); // 显示保存的类型值
}
};
xhr.send("type=" + encodeURIComponent(type)); // 将类型值发送到PHP脚本
}
```
PHP代码(在save.php文件中):
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$type = $_POST["type"];
// 将类型值写入数据库表
$sql = "INSERT INTO myTable (type) VALUES ('$type')";
if ($conn->query($sql) === TRUE) {
echo "Type saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
```
上述代码将选项值作为POST请求的参数发送到save.php文件中,在该文件中将其写入MySQL数据库表,并返回响应来显示保存的类型值。
阅读全文