2014-06-13 144 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