另一种风格的ajax调用

Another style of ajax call

本文关键字:调用 ajax 风格 另一种      更新时间:2023-09-26

我正在做一些纯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>";
?>

由于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
    });
}