weixin_33720078 2016-04-11 09:09 采纳率: 0%
浏览 12

如何停止自动AJAX通话?

I have the following AJAX call to an API,

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  Auto-ON
  <input id="inp" type="checkbox" data-toggle="toggle" />

  <div id="out"></div>


  <script>

  $('#inp').change(function(){
    if (this.checked) {  

      setInterval(function(){
      $.ajax({
              url: 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL',
              dataType: 'jsonp',
              success: function(results) {
                $("#out").append(results.Status + "<br />");   
              }
      });
    },5000);


    }   
   });

  </script>


</body>
</html>

I want an AJAX call for every 5 seconds if the checkbox is ON. The AJAX calls should stop if the checkbox is OFF. What am I missing here?

Here's a link to what I've got so far - http://jsbin.com/quqazofesu/edit?html,output

  • 写回答

2条回答 默认 最新

  • Memor.の 2016-04-11 09:12
    关注

    You need to call clearInterval when this.checked is false. Try this:

    var interval;
    
    $('#inp').change(function() {
        if (this.checked) {  
            interval = setInterval(function(){
                $.ajax({
                    url: 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL',
                    dataType: 'jsonp',
                    success: function(results) {
                        $("#out").append(results.Status + "<br />");   
                    }
                });
            }, 5000);
        } else {
            clearInterval(interval);
        }
    });
    
    评论

报告相同问题?