未捕获的TypeError:无法读取属性'然后'调用函数时未定义的

时间:2016-03-14 00:41:56

标签: javascript jquery

我的剧本出了什么问题,我得到了

  

未捕获的TypeError:无法读取属性'然后'未定义的

这是我的剧本:

<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
function connected() {
    $.ajaxSetup({ cache: false });
    $.ajax({
        type:"get",
        url:"cgi-bin/check",
        success:function(data) {
            if (data.indexOf("192.168.1.1:1080")>-1) {
                var audio = new Audio("on.ogg");
                audio.play();
                document.getElementById("output").innerHTML = "Connected";
                clearTimeout(loop);
            }
        }
    });
    loop = setTimeout(connected, 1000);
}
function disconnected() {
    $.ajaxSetup({ cache: false });
    $.ajax({
        type:"get",
        url:"cgi-bin/check",
        success:function(data) {
            document.getElementById("output").innerHTML = "function disconnected ";
            if (data.indexOf("ssh disconnected")>-1) {
                var audio = new Audio("off.ogg");
                audio.play();
                document.getElementById("output").innerHTML = "Disconnected: "+data;
                clearTimeout(loop);
            }
        }
    });
    loop = setTimeout(disconnected, 1000);
}
function notif() {
    var loop;
    $.ajaxSetup({ cache: false });
    $.ajax({
        type:"get",
        url:"cgi-bin/check",
        success:function(data) {
            if (data.indexOf("192.168.1.1:1080")>-1) {
                document.getElementById("output").innerHTML = "It's connected, waiting to disconnect";
                disconnected().then(connected);
            }
            else {
                document.getElementById("output").innerHTML = "It's disconnected, waiting to connect";
                connected().then(disconnected);
            }
        }
    });
}
notif();
</script>
<p id="output"></p>

这是通知我ssh隧道是否断开/连接的脚本。它会在每次出现时发出声音。

2 个答案:

答案 0 :(得分:0)

除非我遗漏了某些内容,否则您的connected.then()函数不会返回任何内容,并且您正在尝试undefined.then()值。

$model = $model->replicate(); Promise方法

通过你的代码看起来你似乎并不完全理解异步事情是如何工作的,所以我建议你阅读一些资源。

<强> https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

<强> Easy to understand definition of "asynchronous event"?

<强> http://rowanmanning.com/posts/javascript-for-beginners-async/

答案 1 :(得分:0)

参考:http://api.jquery.com/jquery.ajax/

  

弃用通知:jqXHR.success(),jqXHR.error()和   从jQuery 1.8开始,不推荐使用jqXHR.complete()回调函数。准备   你的代码最终删除,使用jqXHR.done(),jqXHR.fail(),   和jqXHR.always()相反。

将代码更改为如下所示:

$.ajax({
        type:"get",
        url:"cgi-bin/check"}).done(function(data) {} );

您可以使用完成然后然后会捕获错误以及成功回复。