Return xmlhttp responseText from function as return

im new in javascript and php, my goal is: RETURN string from xmlhttp responseText for the return value of the function. Therefore, I can use it with the innerText or innerHTML method. html code:

<script> function loadXMLDoc(myurl){ var xmlhttp; if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();} else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");} xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ xmlhttp.responseText;} } xmlhttp.open("GET",myurl,true); xmlhttp.send(); } </script> 
+4
source share
2 answers

Just return the responseText property or assign its value to a variable in the close.

Return value:

 <script> function loadXMLDoc(myurl) { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { return xmlhttp.responseText; } } xmlhttp.open("GET", myurl, true); xmlhttp.send(); return xmlhttp.onreadystatechange(); } </script> 

Using closure:

 <script> var myValue = "", loadXMLDoc = function (myurl) { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { return xmlhttp.responseText; } } xmlhttp.open("GET", myurl, true); xmlhttp.send(); myValue = xmlhttp.onreadystatechange(); }; </script> 
+4
source

You can not.

None of them execute synchronous code, and you should not return anything loadXMLDoc , but an anonymous function, which is the onreadystatechange handler.

Your best shot is to pass a callback function.

 function loadXMLDoc(myurl, cb){ var xmlhttp; if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();} else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");} xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ if( typeof cb === 'function' ) cb(xmlhttp.responseText); } } xmlhttp.open("GET",myurl,true); xmlhttp.send(); } 

And then call it like

 loadXMLDoc('/foobar.php', function(responseText) { // do something with the responseText here }); 
+4
source

Source: https://habr.com/ru/post/1434159/


All Articles