2013-06-28 102 views
0

我在我的home.php中編寫了下面的代碼。點擊提交按鈕調用login()函數。需要幫助來捕捉AJAX響應

function login() 
    { 
    try{ 
     xmlHttp=new XMLHttpRequest(); 
    }catch(e){ 
     try{ 
     xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    }catch(e2){ 
     try{ 
     xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
     }catch(e3){ 

     alert('Sorry ! AJAX not supported'); 
    } 
    } 
    } 
    xmlHttp.onreadystatechange=function(){ 
     if(xmlHttp.readyState==4&&xmlHttp.status==200){ 
     alert(xmlHttp.responseText); 
     } 
    } 
    xmlHttp.open('POST','ajax_call.php',true); 
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); 
    xmlHttp.send(document.getElementById('username').value,document.getElementById('password').value); 
    } 
    </script> 

我ajax_call.php腳本是

<? 
echo 'hello'; 
?> 

我沒有得到警報Hello。爲什麼?

[我試圖提醒readyStatestatus

xmlHttp.onreadystatechange=function(){ 
     alert(xmlHttp.readyState+" "+xmlHttp.status); 
     if(xmlHttp.readyState==4&&xmlHttp.status==200){ 
     alert(xmlHttp.responseText); 
     } 
    } 

和序列得到以下

1 0 
2 200 
3 200 
4 200 
hello 
1 0 
hello 
+0

嘗試從xmlHttp.send刪除參數() – bugwheels94

+0

@Ankit:試過,但沒有幫助 –

+1

所以呃... ...難道這不是意味着你的「你好」不顯示?這是應該發生的,每當有更新請求發生變化時,它從1 200(發送,無狀態碼)變爲2 200(接收,狀態正常),最終變爲4 200(請求就緒,狀態正常)之後你會看到你想要的「你好」......對嗎? –

回答

0
login() 
     { 
     try{ 
      xmlHttp=new XMLHttpRequest(); 
     }catch(e){ 
      try{ 
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     }catch(e2){ 
      try{ 
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
      }catch(e3){ 

      alert('Sorry ! AJAX not supported');Or 
     } 
     } 
     } 
     xmlHttp.onreadystatechange=function(){ 
      if(xmlHttp.readyState==4&&xmlHttp.status==200){ 
      alert(xmlHttp.responseText); 
      } 
     } 
     xmlHttp.open('POST','ajax_call.php',true); 
     xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");/* Anil Remove ;*/ 
     xmlHttp.send('username'.value,'password'.value);/* try static username and password*/ 
     } 
     </script>[ajax call][1] 


    [1]: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_post2 
0

最後一行應該只是

xmlHttp.send(); 

但升ooks喜歡你想做一些認證...如果它是基本認證的價值應該在一個頭,或者如果它是一些孩子的服務器認證,這取決於您的實施...你能解釋爲什麼你有用戶名/密碼在你的xmlHttp.send()調用?

+0

這是一個如何添加基本身份驗證頭btw的示例:http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html我之前使用過本教程,讓它工作... –

+0

:我從登錄表單中選取值,然後使用AJAX記錄用戶。但是在這裏,我只是爲了測試它而放置'hello'。 –

0

只是一個想法:

  • 我想你一定開放您的XMLHTTP 以前的onreadystatechange!

。開的第三個參數告訴XMLHTTP火的onreadystatechange (這就是爲什麼它被設置爲true)

但是,如果這不是BUG:

  • 你嘗試this.responseText
+0

:我都嘗試過但沒有幫助。 –