readyState 一直為0表示對象已建立,串連未建立的狀態
我寫的代碼:
function LoadXMLDoc(url,scope,orderID){ if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } alert(xmlhttp); if(xmlhttp!=null){ xmlhttp.onreadystatechange = changeState(); xmlhttp.open("post",url,true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("scope="+scope+"&orderID="+orderID); } } function changeState(){ alert("q"); alert('state:'+xmlhttp.readyState); alert('status:'+xmlhttp.status); if(xmlhttp.readyState==4 && xmlhttp.status==200){ alert("Q"); window.location.reload(); } }
後來終於解決了,是因為這句:xmlhttp.onreadystatechange = changeState();這樣寫的話xmlhttp.onreadystatechange為將changeState的傳回值賦給xmlhttp.onreadystatechange;而xmlhttp.onreadystatechange為當狀態改變時調用函數changeState,所以應該這樣寫:xmlhttp.onreadystatechange=changgeState,如果有參數的話這樣寫:xmlhttp.onreadystatechange = functiong (){changeState(a,b);};