2014-06-13 141 views
-2

我是新來的ajax,並試圖創建AJAX-> PHP連接。我使用下面的代碼PHP ajax呼叫失敗

file1.php

<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
</head> 
<input type="text" id='demo'> 
<input type="button" onclick='ajaxCall()' value='23' > 
<script> 
function ajaxCall() 
{ 
document.getElementById('demo').value="343434"; 
xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange=function(){ 
    if(xmlhttp.requeststate==4 && xmlhttp.status==200){ 
    document.getElementById('demo').value="4444343434"; 
    document.getElementById('demo').value=xmlhttp.responseText; 
    } 
} 
xmlhttp.open("GET","test.php",true); 
xmlhttp.send(); 
} 
</script> 
</body> 
</html> 

和相應的test.php現在

<?php 
echo "me"; 
?> 

當我按一下按鈕,文本框的值更改爲343434,但不更改AJAX調用,即使它不會更改爲4444343434.我目前正在ubuntu 14.04LTS上運行php 5.5.6。

+1

既然你包含了jquery,可以使用jquery的Ajax方法,而不是用'new XMLHttpRequest'等手工編寫Ajax。確實是 – developerwjk

+0

。使用jquery自己的ajax函數。它會添加你缺少的錯誤處理。你的代碼只是假設一切都會成功。 –

回答

1

變化xmlhttp.requeststatexmlhttp.readyState

嘗試使用以下crossbrowsing功能

function getXmlHttp(){ 
    var xmlhttp; 
    try { 
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
    } catch (e) { 
    try { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } catch (E) { 
     xmlhttp = false; 
    } 
    } 
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') { 
    xmlhttp = new XMLHttpRequest(); 
    } 
    return xmlhttp; 
} 

,並更改xmlhttp = new XMLHttpRequest();xmlhttp = new getXmlHttp();

而且沒有jQuery的這項工作。

+0

在大多數情況下,我不會去支持這種古老版本的IE。 – Quentin

+0

這個工作,你能告訴我我的方法有什麼問題嗎? – user3263192

+0

XMLHttpRequest中沒有'requeststate'屬性。只需'readyState','status'和'onreadystatechange'。請閱讀http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp。 – CnapoB