2010-10-21 28 views
0

这是我的代码:为什么当我通过AJAX下拉选择PHP中的选项总是给我第一个选项?

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']); 
?> 

回答

1

价值的问题不在于得到,挂钩这些是两两件事:

document.getElementById('gene').onclick = xmlhttpPost("generador.php"); 

...你可能会认为,你设置的东西被执行到按钮的onclick事件,但你没有。 该功能将立即执行,而不是点击。

你应该写这样的说法:

document.getElementById('gene').onclick = function(){xmlhttpPost("generador.php");} 

的另一个问题: 一个<button>的默认类型是提交,因此,如果您按一下按钮,表单将sended。 你可以设置按钮的类型为“按钮”或取消通过JavaScript提交表单,否则你的AJAX请求是没用的,因为表单将被发送(并且页面重新载入)

+0

非常感谢莫尔博士,我真的没有太多时间阅读书籍和博客去解决这个问题,这就是为什么我来这里得到一个快速建议,我向你保证,你将成为我第一次展示当我完成它的应用程序 – user478249 2010-10-21 22:35:19

相关问题