store XMLHttpRequest.responseText as variable :(

笑着哭i 提交于 2020-01-17 04:08:06

问题


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

}


回答1:


This is because Ajax is asynchronous, and result isn't set yet when you do this (plus the var makes it local to the function anyway, you'd have to remove that).

The best thing to do would be to move the innerHTML line into the readystatechange callback.

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/5050387/store-xmlhttprequest-responsetext-as-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!