为什么,当我通过Ajax在下拉列表中将所选选项传递给PHP时,它总是给我第一个选项?
这是我的代码:为什么,当我通过Ajax在下拉列表中将所选选项传递给PHP时,它总是给我第一个选项?,php,javascript,ajax,drop-down-menu,Php,Javascript,Ajax,Drop Down Menu,这是我的代码: <html> <head> <script> comenzar = function(){ document.getElementById('gene').onclick = xmlhttpPost("generador.php"); } xmlhttpPost = function(strURL){
<html>
<head>
<script>
comenzar = function(){
document.getElementById('gene').onclick = xmlhttpPost("generador.php");
}
xmlhttpPost = function(strURL){
xmlHttpReq = false;
self = this;
self.xmlHttpReq = new XMLHttpRequest();
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function(){
if(self.xmlHttpReq.readyState == 4){
update(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
getquerystring = function(){
form = document.getElementById('formu');
combi = document.getElementById('sele').options[document.getElementById('sele').selectedIndex].value;
qstr = "tres=" + escape(combi);
return qstr;
}
update = function(resu){
document.getElementById('tag').innerHTML = resu;
}
window.onload = comenzar;
</script>
</head>
<body>
<form id=formu>
<select id=sele>
<option>C</option>
<option>v</option>
</select>
<button id=gene><p>generate</p></button>
</form>
<p id=tag></p>
</body>
</html>
//generador.php
<?php
echo( "tu combinacion" . $_POST['tres'] );
?>
comenzar=函数(){
document.getElementById('gene').onclick=xmlhttpPost(“generador.php”);
}
xmlhttpPost=函数(strURL){
xmlHttpReq=false;
self=这个;
self.xmlHttpReq=新的XMLHttpRequest();
self.xmlHttpReq.open('POST',strURL,true);
self.xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange=函数(){
if(self.xmlHttpReq.readyState==4){
更新(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
getquerystring=函数(){
form=document.getElementById('formu');
combi=document.getElementById('sele')。选项[document.getElementById('sele')。selectedIndex]。值;
qstr=“tres=”+逃逸(组合);
返回qstr;
}
更新=功能(resu){
document.getElementById('tag')。innerHTML=resu;
}
window.onload=comenzar;
C
v
产生
//generador.php
问题不在于获取值。钩子是以下两件事:
document.getElementById('gene').onclick = xmlhttpPost("generador.php");
…您可能认为已将要执行的内容设置为按钮的onclick事件,但您没有这样做。此函数将立即执行,而不是onclick
你应该这样写:
document.getElementById('gene').onclick = function(){xmlhttpPost("generador.php");}
另一个问题是:
的默认类型是submit,因此如果单击按钮,表单将被发送。
您可以将按钮类型设置为“button”或通过JavaScript取消表单提交,否则您的Ajax请求将无效,因为表单将被发送(并重新加载页面)。非常感谢Molle博士,我真的没有太多时间阅读书籍和博客来找到解决方案,这就是我来这里寻求快速建议的原因,我向您保证,您将是我完成申请后第一个向您展示申请表的人