getJSON始终返回相同的数据

时间:2016-03-08 07:46:52

标签: jquery json api getjson

有没有办法刷新getJSON()的数据?我想从API中检索随机图像URL(并设置css background-image)。问题是图像URL保持不变,而每次调用函数时它都会刷新。

function changeImage() {
    $.getJSON("https://api.unsplash.com/photos/random?client_id=336b527b2e18d045045820b78062b95c825376311326b2a08f9b93eef7efc07b", function(result) {
        randomPhoto = result.urls.full;
        console.log(randomPhoto);
    });
};

changeImage();       

jsFiddle这里:https://jsfiddle.net/h2jscr46/

3 个答案:

答案 0 :(得分:2)

直观地,我尝试添加随机数参数,甚至更好的时间戳 试试这个:

$.getJSON("https://api.unsplash.com/photos/random?client_id=3...7b&ts=" + (new Date().getTime())

https://jsfiddle.net/entio/L8rphtno/

答案 1 :(得分:1)

感谢大家的投入!我最终使用了这个:

这是缓存。

var randomPhoto = {};

    function changeImage() {

    $.ajax({
  url: "https://api.unsplash.com/photos/random?client_id=336b527b2e18d045045820b78062b95c825376311326b2a08f9b93eef7efc07b",
  cache: false,
  success: function(result){
    randomPhoto = result.urls.full;
     console.log(randomPhoto);
  }

});

};

    changeImage();

这是JSfiddle https://jsfiddle.net/9xft1orw/1/

当API仍处于开发模式时,它具有速率限制

答案 2 :(得分:0)

尝试使用AJAX来刷新您的数据。

设置缓存false的示例。

$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});
相关问题