2011-12-30 128 views
-1

我已經編寫了一個簡單的應用程序,顯示一份工作的候選人列表,然後,在點擊一個聘請按鈕時,應該改變一個數據庫以反映新僱用的候選人,並將其餘人員顯示爲未被僱用。但是,該功能無法正常工作。我遇到的問題是AJAX函數似乎從來沒有提供響應,我不明白爲什麼。數據庫也沒有得到更新。我的文件在下面。爲什麼這個AJAX功能不能正常工作?

document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";我的html頁面的底部更新一個div,顯示出了readyState爲4,status是200,這應該意味着AJAX功能正常返回,但echo「d響應不正在顯示。即使我從new_hire.php文件中刪除所有代碼,並且只是將文件echo "hello";刪除,responseText中也不會返回任何內容。

resumes.php:

<html> 

<head> 

<script type="text/javascript"> 
function new_hire(name){ 
    var xmlhttp; 
    if (window.XMLHttpRequest){ 
    xmlhttp=new XMLHttpRequest(); 
    } 
    else{ 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange=function(){ 
    document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; 

    //this line, when removed, does not change anything. I left it in for debugging purposes. 
    document.getElementById("errors").innerHTML+=xmlhttp.responseText; 

    if (xmlhttp.readyState=4 && xmlhttp.status=200){ 

     var others = xmlhttp.responseText.split("|"); 

     for (i=0;i<others.length;i++){ 
     tag = others[i].replace(" ","_"); 

     document.getElementById(tag).innerHTML=""; 
     } 
    } 
    } 

    xmlhttp.open("POST","new_hire.php",true); 
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
    xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople"); 

    var name_tag = name.replace(" ","_"); 

    document.getElementById(name_tag).innerHTML="(Current Employee)<br>"; 
} 
</script> 

</head> 

... 

</html> 

new_hire.php(AJAX響應文件):

<?php 

$hiree = $_POST['hiree']; 
$pos = $_POST['position']; 


$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error()); 
mysql_select_db("dbname",$con); 

$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;"); 
mysql_fetch_array($clear); 

$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';"); 
mysql_fetch_array($reset); 

$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;"); 
$array = array(); 

while ($row = mysql_fetch_array($people)){ 
    array_push($array,$row['Name']); 
} 

mysql_close($con); 

$response = join("|",$array); 
echo $response; 

?> 
+0

您無法在readystate之前讀取responseText 4. – epascarello 2011-12-30 17:57:03

+0

我明白,但是當我刪除嘗試這樣做的行時,沒有改變。一定有其他的東西是錯的。 – ewok 2011-12-30 17:58:52

+0

如果將responseText行放在「if(xmlhttp.readyState = 4 && xmlhttp.status = 200){」block? – 2011-12-30 18:18:23

回答

1

請注意,您的if語句沒有使用比較操作符==而是賦值運算符=因此您正在使用:if (xmlhttp.readyState=4 && xmlhttp.status=200)而不是if (xmlhttp.readyState==4 && xmlhttp.status==200)