im是javascript和php中的新增功能,我的目标是:从xmlhttp responseText返回字符串以返回函数的返回值。因此我可以将它与innerText或innerHTML方法一起使用。html代码:
<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>
您不能。
既不同步运行代码,也不对return
进行任何操作,但对[
loadXMLDoc
然后称呼它
function loadXMLDoc(myurl, cb) { // Fallback to Microsoft.XMLHTTP if XMLHttpRequest does not exist. var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if (typeof cb === 'function') cb(xhr.responseText); } } xhr.open("GET", myurl, true); xhr.send(); }
返回值:
loadXMLDoc('/foobar.php', function(responseText) {
// do something with the responseText here
});
使用闭包:
<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>