0

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

<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>";
?>
4

1 回答 1

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
    });
}
于 2013-04-26T06:07:53.677 回答