通过ajax获取单选按钮值到php文件 [英] Get the radio button value through ajax to php file
问题描述
单击单选按钮后,触发 onclick 事件时不会传递单选按钮的值.这是我的代码:
After clicking the radio button, the value from the radio button is not being passed when the onclick event is triggered. Here is my code:
<form name="Form1" id="color" style="font-size: 100%" action="#">
<input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="blue"/>Blue <br /></p>
<p> <input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="red"/>Red
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function MyAlert() {
var radio1=$('input[type="radio"]:checked').val();
var pass_data = {
'radio1' : radio1,
};
alert(pass_data);
$.ajax({
url : "",
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}
</script>
<?php
echo $radio1=$_GET['radio1'];
?>
单击单选按钮时,出现错误
When I click the radio button, I get the error
未定义索引:radio1
Undefined index: radio1
在同一页面中单击时,我想显示单选按钮的值.
I want to display value of the radio button when clicking it within the same page.
推荐答案
首先使ajax到单独的PHP页面,您将在其中访问单选值.收到数据后也要发出警报.
Firstly make ajax to separate PHP page where you will access the radio value. Also make alert after you receive the data.
$.ajax({
url : "post.php",
type : "POST",
data: pass_data,
success : function(data) {
// alert radio value here
alert(data);
}
});
创建一个单独的PHP文件post.php,您可以在其中访问单选输入.由于您正在发出POST请求,因此需要使用$ _POST而不是$ _GET来获取单选按钮值.
Crete a separate PHP file post.php where you access radio input. Since you are making POST request you need to use $_POST instead of $_GET to get radio button value.
<?php
$radio1 = $_POST['radio1'];
echo $radio1;
?>
这篇关于通过ajax获取单选按钮值到php文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!