带有分页功能的Google自定义搜索API [英] Google custom search API with pagination

查看:115
本文介绍了带有分页功能的Google自定义搜索API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法,可将来自Google自定义搜索API的10个结果的链接放入一个数组中:

I have this method that puts the links of the 10 results from the Google custom search API into an array:

require 'json'
require 'open-uri'

def create
    search = params[:search][:search]
    base_url = "https://www.googleapis.com/customsearch/v1?"

    stream = open("#{base_url}key=XXXXXXXXXXXXX&cx=XXXXXXXXXX&q=#{search}&start=#{i}&alt=json")
    raise 'web service error' if (stream.status.first != '200')

    result = JSON.parse(stream.read)

    @new = []
    result['items'].each do |r|
      @new << r['link']
    end
end

和我的观点:

<% @new.each do |link| %>
    <p><%= link %></p>
<% end %>

我在弄清楚如何添加分页时遇到麻烦,因此在第二页上将返回下一个10个结果.我正在使用Kaminari宝石进行分页.

I'm having trouble figuring out how to add pagination with this so that on the second page would return the next 10 results. I'm using the Kaminari gem for pagination.

当用户单击指向另一个页面的链接时,我希望从Google的API中获取接下来的10个结果.您可以使用API​​的start参数来执行此操作,该参数指定以第一个结果开头的结果,我将其作为i传递.我当时正在考虑做这样的事情:

I want for when a user clicks a link to another page, I fetch the next 10 results from Google's API. You can do this with the API's start parameter that specifies the first result to start with, which I pass as i. I was thinking of doing something like this:

i = (params[:page] - 1) * 10 + 1

其中,params[:page]是当前页码,但是由于某些原因,它是不确定的.我也不确定如何为不是AR对象的数组设置分页,以及我认为会怎样.非常感谢您的帮助,随时使用您知道的任何分页宝石.

where params[:page] is the current page number, but for some reason it is undefined. Also I'm unsure about how to setup pagination for an array that is not an AR object, and what would go in my view. I'd appreciate any help, and feel free to use any pagination gem you know.

推荐答案

如何设置params[page]?它需要以某种方式与请求中的其他参数一起传递.

How are you setting params[page]? It needs to be passed in with the other parameters in your request in some way.

也许您的控制器中需要这样的东西:

Perhaps you need something like this in your controller:

@page = params[:page] || 1
i = (@page - 1) * PER_PAGE + 1

stream = open("#{base_url}key=XXXXXXXXXXXXX&cx=XXXXXXXXXX&q=#{search}&start=#{i}&alt=json")
raise 'web service error' if (stream.status.first != '200')

result = JSON.parse(stream.read)
@new = result['items'].map{|r| r['link']}

在您看来,您需要确保通过链接中的query参数传递页面以获取下一组结果.您最有可能希望返回@page + 1.

In your view you need to make sure that you are passing the page via the query parameter in the link to fetch the next set of results. Most likely that you would want to return @page + 1.

使用非ActiveRecord对象处理分页取决于您的分页库.您可能想查看 will_paginate如何处理此问题.

Handling pagination with non ActiveRecord objects depends on your pagination library. You might want to check out how will_paginate handles this.

这篇关于带有分页功能的Google自定义搜索API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆