未捕获的类型错误:调用函数时无法读取未定义的属性“then”

Uncaught TypeError: Cannot read property 'then' of undefined when calling a function

本文关键字:未定义 读取 属性 then 函数 类型 错误 调用      更新时间:2023-09-26

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

捕获的类型错误:无法读取未定义的属性"then"

这是我的脚本:

<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 隧道是否断开连接/连接的脚本。每次出现时,它都会播放声音。

除非我错过了什么,否则您的 disconnectedconnected 函数不会返回任何内容,并且您正在尝试对undefined值执行.then()

.then()是一种Promise方法

从您的代码来看,您似乎并不完全了解异步事物的工作原理,因此我建议您阅读一些有关此的资源。

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

易于理解的"异步事件"定义?

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

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

弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 1.8 开始被弃用。准备 您的代码用于最终删除它们,请使用 jqXHR.done(), jqXHR.fail(), 和 jqXHR.always() 代替。

将代码更改为如下所示:

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

您可以使用完成然后然后将捕获错误以及成功响应。