1 <form name="registF" method="post" action="#">
2 <p>註冊名稱:<input type="text" name="user" /><span id="check"></span></p>
3 <p>註冊密碼:<input type="password" name="pwd" /></p>
4 <p><input type="submit" name="sbm" value="註冊" id="sbm" /></p>
5 </form>
6 <button id="test">Ajax測試</button>
上面是一個很普通的表單
我們要運用Ajax來檢查名稱是否被註冊過
於是:
1 var xhr = {
2 cxhr:new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHttp') || new ActiveXObject('Microsoft.XMLHttp'),
3 request:function(method,url,callback,postVars){
4 xhr.cxhr.onreadystatechange = function(){
5 if(xhr.cxhr.readyState != 4) return;
6 (xhr.cxhr.status == 200) ?
7 callback.success(xhr.cxhr.responseText,xhr.cxhr.responseXML):
8 callback.failure(xhr.cxhr.status);
9 }
10 xhr.cxhr.open(method,url,true);
11 if(method != 'POST' || method != 'post'){
12 postVars = null;
13 }
14 xhr.cxhr.send(postVars);
15 }
16 }
17
18 window.onload = function(){
19 var callback = {
20 success:function(responseText,responseXML){document.getElementById('check').innerHTML = responseText;alert(responseText);},
21 failure:function(statusCode){alert("Failure" + statusCode);}
22 };
23 document.getElementById('sbm').onclick = function(){
24 xhr.request('GET',"test.php",callback);
25 }
26 }
在ff中運行為:
修改一下:
1 window.onload = function(){
2 var callback = {
3 success:function(responseText,responseXML){document.getElementById('check').innerHTML = responseText;alert(responseText);},
4 failure:function(statusCode){alert("Failure" + statusCode);}
5 };
6 document.getElementById('test').onclick = function(){
7 xhr.request('GET',"test.php",callback);
8 }
9 }
再運行一下:
就是說ff不能在提交表單時進行Ajax請求,今天在學習發現的問題,具體為什麼本人也不知道,如有知情者還望指教