我會盡力解釋我的問題。我有4個文件index.html,event.js,start.js和form.php。AJAX和回調函數
的index.html
<head><script type="javascript/text" src="start.js></script></head>
<html>
<button id="bt" type="button">Click</button>
<div id="test"></div>
</html>
start.js
window.onload=init;
function init(){
document.getElementById("bt").onclick=function(){
getFile('form.php?x='+Math.random()*11, getPHP);
getFile('javascripts/event.js?x='+Math.random()*11,getJS);
}
}
function getFile(source,callFunc){
var xmlHttpR=false;
if (window.XMLHttpRequest)
xmlHttpR=new XMLHttpRequest();
else if (window.ActiveXObject)
xmlHttpR=new ActiveXObject("Microsoft.XMLHttp");
else
alert("Error");
if (xmlHttpR){
xmlHttpR.open("GET",source,true);
xmlHttpR.onreadystatechange=function(){
if (xmlHttpR.readyState==4 && xmlHttpR.status==200){
callFunc(xmlHttpR);
delete xmlHttpR;
xmlHttpR=null;
}
}
}
xmlHttpR.send(null);
}
function getPHP(response){
document.getElementById("test").innerHTML=response.responseText;
}
function getJS(response){
eval(response.responseText);
}
event.js
document.getElementById("firstName").onblur=function(){
validate(this.name,this.value);
}
form.php的
<html>
<form>
<input type="text" id="firstName" value="">
</form>
</html>
好了,現在的問題是,當onblur事件在firstName上觸發時什麼也沒有發生,但是當我刷新頁面有時一次或兩次時,事件正常運行。也許我沒有在正確的時間得到答覆?
回調函數和eval是否有問題,我用onblur事件分配給firstName字段?
是與AJAX異步調用的問題?我應該使用同步嗎?我錯過了什麼?
我希望我能解釋清楚問題所在。
在此先感謝您的幫助。
謝謝,我試過了,但沒有奏效。我得到了form.php,但它沒有顯示在測試div中,我沒有得到event.js。有任何想法嗎? – codemaker 2009-12-11 02:04:13
oops,忘記了您需要將響應傳遞給getPHP。應該將form.php的內容放入div#test中。 – jonnyheadphones 2009-12-11 03:37:15
@jonnyheadphones:它完美的作品。非常感謝您的幫助。 – codemaker 2009-12-11 18:53:04