来自 google 的随机图像设置为使用图像关键字查询的背景

random image from google set as background using query for image keyword

我有这个代码:

<html>
<head>
    <title></title>
    <script src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
    google.load('search', '1');
    google.setOnLoadCallback(OnLoad);
    var search;

    //i suggest instead of this to make keywords list so first to pick random keyword than to do search and pick random image
    var keyword = 'cute kittens';

    function OnLoad()
    {
        search = new google.search.ImageSearch();

        search.setSearchCompleteCallback(this, searchComplete, null);

        search.execute(keyword);
    }

    function searchComplete()
    {
        if (search.results && search.results.length > 0)
        {
            var rnd = Math.floor(Math.random() * search.results.length);

            //you will probably use jQuery and something like: $('body').css('background-image', "url('" + search.results[rnd]['url'] + "')");
            document.body.style.backgroundImage = "url('" + search.results[rnd]['url'] + "')";
        }
    }
    </script>
</head>
<body>

它应该给我一张小猫的照片然后将其作为背景,但它没有给我任何背景,有人知道如何解决这个问题吗?如果你这样做,请帮忙。这看起来像是重复的,但是我从之前的 post 获得了代码,但它不起作用,所以请不要标记为重复,我尝试以多种方式修改代码,none 有效,当我的设备关闭时,我丢失了不同的编辑,所以我没有那些。 (我是一个糟糕的开发者,没有保存)

看来 API 自 2011 年以来已被弃用。Google 可能已完全关闭该服务,因为他们的弃用政策允许他们根据以下条款之一这样做

如果出现以下情况,

Google 保留自行决定立即停止提供服务的全部或任何部分弃用版本的权利,恕不另行通知:

  • 根据 Google 合理的善意判断,提供服务的弃用版本可能会造成巨大的经济负担;或
  • 提供服务的弃用版本可能会造成安全风险或 material 技术负担,这由 Google 在其合理的善意判断中确定。

https://developers.google.com/terms/deprecation

我将您的代码放在此处的 JSfiddle 中:https://jsfiddle.net/zcthpd4L/6/ 并遇到错误:

Uncaught TypeError: Cannot read property 'ImageSearch' of undefined
at OnLoad ((index):52)
at (index):70

这似乎不是配置问题造成的,很可能是因为该服务不再可用。最好的办法是使用自定义搜索 api:https://developers.google.com/custom-search/