2013-04-26 28 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