weixin_33676492 2017-12-02 22:46 采纳率: 0%
浏览 37

$ .getJSON + setInterval

I get some data from JSONP file by below code:

$.getJSON('http://static.eska.pl/m/playlist/channel-108.jsonp?callback=?' );
function jsonp(data) { 
document.getElementById("artist").innerHTML = data[0].artists[0].name;
document.getElementById("title").innerHTML = data[0].name;
 };
<!DOCTYPE html>
<head>
    <title>JSONP EskaRock </title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
<div id="artist"></div>
<div id="title"></div>
</body>
</html>

It works, but I need refresh data every 10 sec. I use setInterval function but console FireFox return error "ReferenceError: jsonp is not defined (...channel-108.jsonp:1:1)". My code with setInterval:

setInterval( function () {
$.getJSON('http://static.eska.pl/m/playlist/channel-108.jsonp?callback=?' );
function jsonp(data) { 
document.getElementById("artist").innerHTML = data[0].artists[0].name;
document.getElementById("title").innerHTML = data[0].name;
};
}, 10000)
<!DOCTYPE html>
<head>
 <title>JSONP EskaRock </title>
 <script src="http://code.jquery.com/jquery-latest.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
<div id="artist"></div>
<div id="title"></div>
</body>

</html>

Where's the problem?

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33725126 2017-12-02 23:05
    关注

    You are declaring the function inside the setInterval move it outside and it will work

    function jsonp(data) {
      document.getElementById("artist").innerHTML = data[0].artists[0].name;
      document.getElementById("title").innerHTML = data[0].name;
    };
    setInterval(function() {
      $.getJSON('http://static.eska.pl/m/playlist/channel-108.jsonp?callback=?');
    
    }, 10000)
    <!DOCTYPE html>
    
    <head>
      <title>JSONP EskaRock </title>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    
    </head>
    
    <body>
      <div id="artist"></div>
      <div id="title"></div>
    </body>

    </div>
    
    评论

报告相同问题?