Why can't I return a responseText from an Ajax function?

Here is part of my Ajax function. For some reason that I can’t understand, I can warn () the responseText, but fail to return the responseText. Can anyone help? I need this value to be used in another function.

http.onreadystatechange = function(){ if( http.readyState == 4 && http.status == 200 ){ return http.responseText; } } 
+6
javascript ajax return alert
source share
3 answers

You cannot handle the return value returned from your asynchronous callback. You must handle responseText directly in the callback or call a helper function to handle the response:

 http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { handleResponse(http.responseText); } } function handleResponse (response) { alert(response); } 
+5
source share

What about:

 function handleResponse (response) { return response; } 

which return undefined for synchronous and asynchronous modes

0
source share
 function getdata(url,callback) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var result = xmlhttp.responseText; callback(result) } } xmlhttp.open("POST",url,true); xmlhttp.send(); } 

send the name of the callback function as the second argument to this function. You can get the response text for this function. just. But you cannot directly return anything from an asynchronous call.

0
source share

All Articles