2010-10-21 31 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

相關問題