函数未将值作为参数传递

Function not passing value as argument

本文关键字:参数传递 函数      更新时间:2023-09-26

我不明白为什么getMoreInfoResults()函数没有将单选按钮的值(当选择单选按钮时)传递给GET请求。有人知道为什么吗?

<form name="question_form">
    <input type="radio" name="vote" value="1" onclick="getVote(this.value)" />Yes<br />
    <input type="radio" name="vote" value="2" onclick="getVote(this.value)" />No<br />
    <textarea rows="3" name="moreInfo" onkeyup="getMoreInfoResults(document.question_form.vote.value, this.value)" /></textarea><br />
    <input type="submit" value="Submit" />
    <div id="otherAnswers"></div>
</form>

这是我的javascript:

function getMoreInfoResults(vote, input) {
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 (xmlhttp.readyState==4 && xmlhttp.status==200) {
  document.getElementById("otherAnswers").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","phpPoll/phpPoll_userDefined/functions/getMoreInfoResults.php?vote=" + vote + "&moreInfo=" + input,true);
xmlhttp.send();
}

谢谢。

document.question_form.vote表达式将为您提供NodeList对象,而不是Node对象。显然,它的value性质是undefined

一个可能的解决方法是创建一个函数来检索选中单选按钮的值:

function getCheckedValue(radioNodes) {
    for (var i = 0, l = radioNodes.length; i < l; i++) {
        if (radioNodes[i].checked) {
            return radioNodes[i].value;
        }
    }
}

并使用它而不是直接查询值:

onkeyup="getMoreInfoResults(getCheckedValue(document.question_form.vote), this.value)"