What's wrong with my script, I get
Uncaught TypeError: Cannot read property 'then' of undefined
This is my script:
<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>
That is the script to notify me whether my ssh tunnel gets disconnected / connected. It'll play a sound on each occurence.
Unless I am missing something, your disconnected
and connected
functions do not return anything, and you are trying to do .then()
to an undefined
value.
.then()
is a Promise
method
By the look of your code it seems that you do not fully understand how asynchronous things work, so I would suggest you read a few resources on that.
Easy to understand definition of "asynchronous event"?
http://rowanmanning.com/posts/javascript-for-beginners-async/
Ref: http://api.jquery.com/jquery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Change your code to look something like this:
$.ajax({
type:"get",
url:"cgi-bin/check"}).done(function(data) {} );
You may use done or then . then will catch errors as well as success responses.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.