weixin_33744141 2013-04-26 05:55 采纳率: 0%
浏览 12

Ajax调用的另一种样式

I am doing some experiments with AJAX calls in pure Javascript, no JQuery. I wonder if I can populate a DIV tag like this:

<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>

The problem is how to return the result from ajax_call? My code is as follows, but not working:

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

Remote file:

<?php
  echo "<h1>Jus an experiment</h1>";
?>
  • 写回答

1条回答 默认 最新

  • elliott.david 2013-04-26 06:07
    关注

    It will not work because of the asynchronous nature of AJAX requests. The ajax_call method will return before the server responds with the html that is why you are getting undefied.

    The solution here is to use a callback to do the post processing of ajax response as shown below.

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

    And

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能