通俗易懂解释轮询,侦听和回调区别
轮询:过10分钟就到女朋友宿舍前面去看她有没有回来、没回来我就再去打游戏。
监听:我搬个凳子坐到她宿舍前、直到她回来。
回调:在她门口贴个条子:回来后请打电话至011 。
一、什么是轮询
<html>
<head>
<title></title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var getting = {
url:'www.baidu.com',
dataType:'json',
success:function(result) {
console.log(result);
}
};
//Ajax定时访问服务端,不断获取数据 ,这里是1秒请求一次。
window.setInterval(function(){$.ajax(getting)},1000);
</script>
</body>
</html>
二、什么是侦听
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Event</title>
<script type="text/javascript">
function addEventHandler(target,type,func){
if(target.addEventListener){
//监听IE9,谷歌和火狐
target.addEventListener(type, func, false);
}else if(target.attachEvent){
target.attachEvent("on" + type, func);
}else{
target["on" + type] = func;
}
}
function removeEventHandler(target, type, func) {
if (target.removeEventListener){
//监听IE9,谷歌和火狐
target.removeEventListener(type, func, false);
} else if (target.detachEvent){
target.detachEvent("on" + type, func);
}else {
delete target["on" + type];
}
}
var eventOne = function(){
alert("第一个监听事件");
}
function eventTwo(){
alert("第二个监听事件");
}
window.onload = function(){
var bindEventBtn = document.getElementById("bindEvent");
//监听eventOne事件
addEventHandler(bindEventBtn,"click",eventOne);
//监听eventTwo事件
addEventHandler(bindEventBtn,"click",eventTwo );
//监听本身的事件
addEventHandler(bindEventBtn,"click",function(){
alert("第三个监听事件");
});
//取消第一个监听事件
removeEventHandler(bindEventBtn,"click",eventOne);
//取消第二个监听事件
removeEventHandler(bindEventBtn,"click",eventTwo);
}
</script>
</head>
<body>
<input type="button" value="测试" id="bindEvent">
<input type="button" value="测试2" id="yuanEvent">
</body>
</html>
三、什么是回调
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
});
</script>
<script>
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "www.baidu.com",
type: "POST",
data: {id : menuId},
dataType: "html"
});
//调用成功时的回调处理
request.done(function(msg) {
$("#log").html( msg );
});
//调用失败时的回调处理
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
</script>
</head>
<body>
<div id="div1"><h2>使用 jQuery AJAX 修改文本内容</h2></div>
<button>获取其他内容</button>
</body>
</html>