将XMLHttpRequest.responseText存储为变量:(

时间:2011-02-19 11:00:46

标签: php javascript ajax responsetext

<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);

}

3 个答案:

答案 0 :(得分:2)

这是因为Ajax是异步的,并且当你执行此操作时尚未设置result(加上var无论如何都使它成为函数的本地,你必须删除它)。

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

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

答案 1 :(得分:1)

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

//this is in the global scope
//so it's available anywhere

**var result;**

function ajaxFunction(){

    var path = 'http://localhost/php/';
    var fileName = 'yourCode.php';


    var ajaxRequest;  // The variable that makes Ajax possible!

    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){
                       **result = ajaxRequest.responseText;**
        }
    }


    ajaxRequest.open("GET", path+fileName, true);
    ajaxRequest.send(null); 
}

</script>

答案 2 :(得分:0)

ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      result = ajaxRequest.responseText;        
    }
}
ajaxRequest.open("GET", "vartest.php", true);
document.getElementById('span').innerHTML = result;
ajaxRequest.send(null);
}