<script language="javascript" type="text/javascript">




try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
var result = ajaxRequest.responseText;
    }
}
ajaxRequest.open("GET", "vartest.php", true);
document.getElementById('span').innerHTML = result;
ajaxRequest.send(null);


}

最佳答案

这是因为Ajax是异步的,并且当您执行此操作时尚未设置result(加上var使其始终在该函数中本地存在,您必须将其删除)。

最好的办法是将innerHTML行移到readystatechange回调中。

ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
   document.getElementById('span').innerHTML = ajaxRequest.responseText;;
}

10-06 08:00