仅使用JavaScript的Yahoo API搜索

Previously I've mentioned how I do image searches with my bigger daughter, hunting for images of Cinderella, Ariel the little mermaid, and other equally beautiful princesses. So I thought why not build a custom little app for the little kid to do this, I mean, her, being the good (and beautiful) girl that she is, totally deserves it. Here are the very basics of such an app, my idea was to do a little demo how you can consume Y! services to do web and image searches, using nothing but JavaScript. Look ma, no server! 😉

之前我曾提到过如何与大女儿进行图像搜索,寻找灰姑娘,小美人鱼爱丽儿(Ariel)以及其他同样美丽的公主的图像。 因此,我想为什么不为这个孩子构建一个定制的小应用程序来做到这一点呢,我的意思是,她是她的好(和美丽)女孩,完全值得。 这是此类应用程序的最基础知识,我的想法是做一些演示如何使用Y! 仅使用JavaScript即可进行网络和图像搜索的服务。 看,没有服务器! 😉

» demo

»演示

仅JS(JS alone)

The cool think about Y! web services is that they provide you different options for the output format of the results they return. You can get XML, php serialized string or JSON. (No SOAP, thank you very much!). I think more companies should consider such an offer, I mean since you get your service to work, the output format is just a ... a format, nothing special.

酷想Y! Web服务是它们为返回的结果的输出格式提供不同的选择。 您可以获取XML,php序列化字符串或JSON。 (没有SOAP,非常感谢!)。 我认为,更多的公司应该考虑提供这样的服务,我的意思是,既然您可以使用自己的服务,那么输出格式只是...一种格式,没什么特别的。

How do you make the request? With JavaScript includes, meaning you use DOM methods to sreate a new <script> tag and add it to the head of your page. The src attribute of the new script tag points to the Y! service, a longish kind of URL with a bunch of parameters.

您如何提出要求? 使用JavaScript includes ,意味着您使用DOM方法创建一个新的<script>标记并将其添加到页面的head 。 新脚本标签的src属性指向Y! 服务,一种带有很多参数的冗长的URL。

When making your request, you say that the output format should be JSON. Then you provide a callback function name. What Y! service does is it calls the function you gave, passing the JSON output as a parameter. Let's say you made a request to: http://..../...&output=json&callback=myfunction and we assume the result of your request is an array: [1,2,3] The Y! service will write out: myfunction([1,2,3]) At the end, your function gets called, receiving the response from the call to the Y! service. It's now up to this function to decide what to do with the result.

发出请求时,您说输出格式应为JSON。 然后,您提供一个回调函数名称。 什么呀! 服务所做的是调用给定的函数,并将JSON输出作为参数传递。 假设您向以下地址发出了请求:http://..../...&output=json&callback=myfunction,我们假设您的请求结果是一个数组: [1,2,3] Y! 服务将写出: myfunction([1,2,3])最后,将调用您的函数,并接收对Y的调用的响应! 服务。 现在由该功能决定如何处理结果。

实作 (Implementation)

It all starts with a simple form and a placeholder for the result:

一切都以简单的形式和占位符开头,以表示结果:

<body>
<form
    action=""
    method="get"
    onsubmit="ysearch.doSearch(
                this[0].value, 
                'content', 
                this[1].checked
              ); 
              return false;">
  <input />
  <input type="checkbox" />Image search
  <input type="submit" value="go!"/>
</form>
<div id="content">&nbsp; </div>
</body>

Submitting this form calls the doSearch() method of the ysearch class.

提交此表单将调用ysearch类的doSearch()方法。

ysearch class has a few properties:

ysearch类具有一些属性:

// url of the image search service
this.image_url = "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?";
// url of the web search service
this.web_url = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?";
 
// ID of element that will
// display the result
this.where = '';
// is this an image search?
this.image_search = false;
 
// parameters for the search
this.url = "output=json"+
           "&callback=ysearch.process" +
           "&appid=YahooDemo" +
           "&start=1" +
           "&results=5" +
           "&query=";
 
// reference to the last included script
this.last_include = false;

Then comes the doSearch method. It does the following:

然后是doSearch方法。 它执行以下操作:

  1. Checks input parameters to see if this is a request for a web search or an image search. The two types af searches use a different web service with a different URL

    检查输入参数以查看这是对Web搜索还是对图像搜索的请求。 搜索的两种类型使用具有不同URL的不同Web服务
  2. Appends the search query to the URL

    将搜索查询附加到URL
  3. Creates a new script tag with SRC that was just figured out

    用刚发现的SRC创建一个新的script标签

  4. Saves a reference to the new script tag, so that it can be cleaned up with the next search

    保存对新脚本标记的引用,以便下次搜索时可以将其清除

Here's the actual code for the doSearch() method:

这是doSearch()方法的实际代码:

this.doSearch = function(q, where, web_image) {
 
  this.where = where;
 
  var script_filename = "";
  if (web_image) {
      script_filename = this.image_url;
      this.image_search = true;
  } else {
      script_filename = this.web_url;
      this.image_search = false;
  }
 
  script_filename += this.url + escape(q);
  var html_doc = document.getElementsByTagName('head').item(0);
  // remove the last included script, we don't need it anymore
  if (this.last_include) {
      html_doc.removeChild(this.last_include);
  }
  var js = document.createElement('script');
  js.setAttribute('type', 'text/javascript');
  js.setAttribute('src', script_filename);
  html_doc.appendChild(js);
 
  // set the pointer to the last include
  this.last_include = js;
 
};

Becuase we passed the callback function name ysearch.process to the service, the new Y! script will call it, passing the search results as an object. Let's see what process() does, really nothing but looping through the results object (description of the object here and here) and spitting out HTML using the politically incorrect innerHTML. Here's the code:

因为我们将回调函数名称ysearch.process给了服务,即新的Y! 脚本将调用它,并将搜索结果作为对象传递。 让我们看看process()的作用,除了循环遍历结果对象(此处此处的对象说明),然后使用政治上不正确的innerHTML吐出HTML外,实际上什么也没做。 这是代码:

this.process = function(resp) {
 
  if (resp.ResultSet && resp.ResultSet.totalResultsReturned > 0) {
    // loop through the results
    var out = '';
    for (var i = 0,
     max = resp.ResultSet.Result.length;
     i < max;
     i++) {
 
    var item = resp.ResultSet.Result[i];
    if (this.image_search) {
      out += '<p><a href="' + item.Url + '">'
      out += '<img src="' + item.Thumbnail.Url + '" /><\/a>';
      out += '<br />' + item.Summary + '<\/p>';
    } else {
      out += '<p><a href="' + item.Url + '">' + item.Title + '<\/a>';
      out += '<br />' + item.Summary + '<\/p>';
    }
 
    }
    document.getElementById(this.where).innerHTML = out;
  } else {
    alert('no results');
  }
}

Tell your friends about this post on Facebook and Twitter

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/yahoo-api-search-with-javascript-alone/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值