HTML获取radio的值

问题描述:

最近在学习PHP,需要做一个投票界面,在另一个界面中获取投票的结果。实现如下:



代码如下:

为了看起来更加简洁,这里只显示body部分

<body>
<form name="form3" method="post" action="ee.php">
	<table>
    	<tr>
            <td><input name="lan" type="radio" value="PHP" />PHP</td>
            <td><input name="lan" type="radio" value="ASP" />ASP</td>
            <td><input name="lan" type="radio" value="JSP" />JSP</td>
            <td><input name="lan" type="radio" value="ASP.NET" />ASP.NET</td>
            <td><input  name="submit" type="submit" value="提交" /></td>
        </tr>
        </table>
        </form>
</body>

ee.php:

<body>
<?php
	if(isset($_POST["submit"])&&$_POST["submit"]=="提交")
	{
		echo "您的选择是:".$_POST["lan"];
	}
?>
</body>
使用input radio做一组单选按钮,这里要注意name的名称必须相同,否则则不是一个组,即不再是单选。

在ee.php中$_POST["lan"]返回的是所选择的那项选项的value的值。

action="ee.php"
上面的一行代码负责将两个php文件链接起来,使得提交按钮按下后,页面会跳转到ee.php这个文件中。
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您使用的是 Golang 和 Gin 框架来处理后端的逻辑,获取 HTMLradio 选择的则需要在前端页面使用 JavaScript 将选中的传递给后端。这里提供一种示例代码: 前端 HTML 文件: ```html <form> <input type="radio" name="radio_name" value="value_1"> Value 1<br> <input type="radio" name="radio_name" value="value_2"> Value 2<br> <input type="radio" name="radio_name" value="value_3"> Value 3<br> <button type="button" onclick="submitForm()">Submit</button> </form> <script> function submitForm() { var radios = document.getElementsByName('radio_name'); var selected_value; for (var i = 0; i < radios.length; i++) { if (radios[i].checked) { selected_value = radios[i].value; break; } } fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ selected_value: selected_value }) }).then(response => { console.log(response); }); } </script> ``` 后端 Golang 代码: ```go package main import ( "fmt" "net/http" ) type RequestBody struct { SelectedValue string `json:"selected_value"` } func main() { router := http.NewServeMux() router.HandleFunc("/submit", func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } var reqBody RequestBody if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } selectedValue := reqBody.SelectedValue fmt.Fprintf(w, "Selected value: %s", selectedValue) }) http.ListenAndServe(":8080", router) } ``` 这里使用 fetch API 将选中的以 JSON 格式传递给后端的 `/submit` 接口,后端则使用 `json.NewDecoder()` 函数解析传递过来的 JSON 请求体,从而取得选中的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值