使用 PHP 和 AJAX 提交单选按钮



我在使用 PHP 和 AJAX 提交无线电输入值时遇到问题。我已经构建了下面的代码,但我似乎无法让它工作。有什么想法吗?单选字段的值仅在按下按钮时才需要传递

<script>
function showUser(str) {
if (str == "myvalue") {
document.getElementById("txtHint").innerHTML = "";
/// location of new code -start
document.querySelector('input[name="users"]:checked').value;
/// location of new code -end
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
<form>
<input type="radio" name="users" value="1">
<input type="radio" name="users" value="2">
<!-------unable to pass value----------->
<input type="button" value="myvalue" onclick="showUser(this.value)">
<!-------unable to pass value----------->
</form>
<div id="txtHint">echo results here</div>

ajax-php.php

<?php
$q = intval($_GET['q']);
echo $q;
?>

谢谢。

传递给showUser函数的"this.value"参数的作用域为具有onclick函数的元素。 因此,它正在尝试发送没有值的按钮元素的值。

你正在做的事情很好。

<input type="button" onclick="showUser(this.value)">

函数showUserbutton类型输入字段调用。并且该字段没有值。

如果要发送任何值,请使用值attribute。例如:

<input type="button" value="mayValue" onclick="showUser(this.value)">

若要访问单选按钮值,可以使用此代码。

document.querySelector('input[name="users"]:checked').value;

要发送单选按钮值,请按照下面的代码进行操作

//xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.open("GET", "ajax-php.php?q=" + document.querySelector('input[name="users"]:checked').value, true);

最新更新