Getting value from Ajax request in variable

时间:2016-04-07 10:43:24

标签: javascript ajax variables

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

3 个答案:

答案 0 :(得分:0)

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 i.e.

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您在请求回调通过更改之前提醒somous4。在这种情况下,命令块首先执行 ,而不是请求回调

作为PHP的服务器端语言自动工作,因此您不需要在那里使用事件。它在请求未完成时休眠。这是因为命令阻止了事件回调