首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

ajax回调函数有关问题

2013-03-14 
ajax回调函数问题最近在学习ajax,教程中提到这个一个例子:function getText(url, callback) {var request

ajax回调函数问题
最近在学习ajax,教程中提到这个一个例子:


function getText(url, callback) {
    var request = new XMLHttpRequest();         // Create new request
    request.open("GET", url);                   // Specify URL to fetch
    request.onreadystatechange = function() {   // Define event listener
        // If the request is compete and was successful
        if (request.readyState === 4 && request.status === 200) {
            var type = request.getResponseHeader("Content-Type");
            if (type.match(/^text/))            // Make sure response is text
                callback(request.responseText); // Pass it to callback
        }
    };
    request.send(null);                         // Send the request now
}



我把上面的代码运用起来:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
  <script type="text/javascript">
      function getText(url) {   
    var request = new XMLHttpRequest();         // Create new request
    request.open("GET", url);                   // Specify URL to fetch
    request.onreadystatechange = function () {   // Define event listener
        // If the request is compete and was successful
        if (request.readyState === 4 && request.status === 200) {
            var type = request.getResponseHeader("Content-Type");
            //myfun(type);
            myTest(request.responseText);
        }
    };
    request.send(null);                         // Send the request now
}
function myTest(str) {
    document.getElementById('A3').innerHTML = str;


}
 </script>


<p><b>Response:</b>
<br /><span id="A3"></span>
</p>


 <button onclick="getText('/js/mytest.htm')">Get TEXT</button>
</body>
</html>



这里面只用了一个 function getText(url)参数,可以正常显示,但是如果是:function getText(url,myTest())就不显示了,不知道为什么这个callback是怎么用的,最好是能有个实例
[解决办法]
你只定义了带一个参数的方法function getText(url) { ...}。。。。给他两个参数肯定不行啊
如果需要带两个参数。再定义一个带两个参数的方法function getText2(url, func) {//func就是你的那个myTest方法名 。。。。

注意javascript不支持方法重载,必须重新起名字

我也是新手,凭个人理解应该是这个问题
[解决办法]
7楼的,JavaScript根本就没有方法重载这回事儿,你去研究下Function的arguments属性。

楼主原来代码的错误是把函数调用的执行结果(带括号)当作参数而不是把函数名(不带括号)作为参数。

热点排行