2013-04-26 33 views
0

我正在做一些实验,使用纯Javascript的AJAX调用,没有JQuery。我想知道是否可以像这样填充DIV标签:另一种Ajax调用

<script type="text/javascript"> 
function call_test() { 
    document.getElementById("myId").innerHTML = ajax_call("example.php?id=1") ; 
} 
</script> 
<body> 

<input type="button" onClick="call_test()" value"Test"> 

<div id="myId">Result should be here</div> 

问题是如何从ajax_call返回结果?我的代码如下,但不工作:

function ajax_call(remote_file) 
{ 
    var $http, 
    $self = arguments.callee ; 
    if (window.XMLHttpRequest) { 
     $http = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
     try { 
      $http = new ActiveXObject('Msxml2.XMLHTTP'); 
     } catch(e) { 
      $http = new ActiveXObject('Microsoft.XMLHTTP'); 
     } 
    } 
    if ($http) { 
     $http.onreadystatechange = function() { 
      if (/4|^complete$/.test($http.readyState)) { 
       return http.responseText ; // This only return undefined 
      } 
     }; 
     $http.open('GET', remote_file , true); 
     $http.send(null); 
    } 
} 

远程文件:

<?php 
    echo "<h1>Jus an experiment</h1>"; 
?> 
+0

'的document.getElementById( “MYID”)的innerHTML = ajax_call( “使用example.php ID = 1?”);'表示'ajax_call'不得使用任何异步请求方法。查看JavaScript_或类似主题中的_synchronous请求。 – Zeta 2013-04-26 06:06:19

+0

好的,非常感谢 – 2013-04-27 04:55:45

回答

2

它不会因为AJAX请求的异步性质的工作。 ajax_call方法将在服务器响应html之前返回,这就是为什么你会得到undefied

这里的解决方案是使用回调进行ajax响应的后处理,如下所示。

function ajax_call(remote_file, callback) { 
    var $http, $self = arguments.callee; 
    if (window.XMLHttpRequest) { 
     $http = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
     try { 
      $http = new ActiveXObject('Msxml2.XMLHTTP'); 
     } catch (e) { 
      $http = new ActiveXObject('Microsoft.XMLHTTP'); 
     } 
    } 
    if ($http) { 
     $http.onreadystatechange = function() { 
      if (/4|^complete$/.test($http.readyState)) { 
       if (callback) 
        callback(http.responseText); 
      } 
     }; 
     $http.open('GET', remote_file, true); 
     $http.send(null); 
    } 
} 

而且

function call_test() { 
    ajax_call("example.php?id=1", function(html) { 
     document.getElementById("myId").innerHTML = html 
    }); 
} 
+0

非常感谢您的回复,让我再次托盘:p – 2013-04-26 06:15:01