为什么简单的google web搜索通过getJSON始终有效?

时间:2011-09-15 11:45:50

标签: javascript jquery json google-search-api

通过谷歌API进行简单的网络搜索是不稳定的。有时它返回4个第一个发现(应该如此),有时JSON认为它是“成功”但responseData是null。为什么我会遇到这些不一致的问题?这是一个异步问题吗?如何让它更稳定? (当我在谷歌搜索图像时,它是稳定的)

var baseUrl = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=0&q="; 
var searchTerm = "obama"; //Lots of hits

$(document).ready(function() // don't do anything until the document is loaded.
{  
$.getJSON(baseUrl + searchTerm +  "&callback=?", function(json) // call getJSON providing the complete url with search term and a JSONP callback
    {
    $.each(json.responseData.results, function(i, gResults){  
        console.log("title: " + gResults.titleNoFormatting);
    });
  });
});

当它失败时,我在json数据结构中找到它:

json.responseDetails: "Suspected Terms of Service Abuse. Please see
  http://code.google.com/apis/errors"

所以谷歌认为我用太多的请求攻击它。我是否必须设置API密钥?现在我只包括

<meta name="google-site-verification" content="myAPIkey-Herevbng66r" />

但是我在我的本地电脑上运行,所以也许它无济于事......

1 个答案:

答案 0 :(得分:0)

试试这个:

function(json) // call getJSON providing the complete url with search term and a JSONP callback
    {
       if (json.responseData === null)
          console.log("json returned nothing");
       else
         $.each(json.responseData.results, function(i, gResults){  
             console.log("title: " + gResults.titleNoFormatting);
         });
  });
});
相关问题