简体   繁体   中英

Getting value from Ajax request in variable

I've this function.

function ajaxtakesource4(callback){
    var ajaxRequest;  // The variable that makes Ajax possible!
    try{
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                alert("Your browser broke!");
                return false;
            }
        }
    }   
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange =function(){
        if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
            var sourcetest = ajaxRequest.responseText;  
            callback(sourcetest);
        }
    }
    ajaxRequest.open("POST", "takesource4.php", true);
    ajaxRequest.send(null); 
}

Also:

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
    });
    alert(somous4);
}

and here I call the above the function:

<div id="run">
  <button id="button_run" class="button" onclick="run()">Run</button>
</div>

When I click on the button it's supposed to alert response from Ajax request, but looks to be alerting a falsy value ( undefined ), as seen in this line:

alert(somous4);

Asynchronous code executes concurrently in nature. Thus, your alert statement may execute before your callback executes (callback will only after it receives back data from server). Put the alert inside the callback and it will show the value returned ie

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
        alert(somous4);
    });
}

Edit: Based on OP's comment, instead of thinking about return values, do this:

function foo(soumous4) { // use somous4 for whatever you want... }

// Call this function foo inside the callback.
ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
        foo(somous4);
    });

I suggest you change the callback in the run function as follows:

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
        alert(somous4);
    });
}

You're alerting somous4 before it's changed by the request callback. In this case the commands block executes first than the request callback .

Server-side languages as PHP does the work automatically , so you don't need to use events there. It sleeps while the request is not done. That's because the commands block turns the event callback .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM