GiantBomb API工作

时间:2014-04-07 16:56:57

标签: javascript jquery html json search

我已经创建了一个帐户,并且我的api键目前只需要一个简单的搜索框和按钮,当点击时会列出游戏和该游戏的图像

已关联以下网站信息

http://www.giantbomb.com/api/documentation

我想运行is并使用json和jquery获取输出任何帮助欢迎

这是一个工作搜索现在一些不允许用户输入新值并且出现问题的图像

两个主要问题不会加载图像只是说未定义,并且无法弄清楚如何只有当用户输入新标题时才能进行完整搜索

   <html>
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

        <script>
    $(document).ready(function(){
            $.ajax({
              url: "http://api.giantbomb.com/search/",
              type: "get",
              data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
              dataType: "jsonp"
            });
    });

    function gamer(data) {
              var table = '<table>';
              $.each( data.results, function( key, value ) {
              table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
            });
                table += '</table>';
            $('#myelement').html(table);
    }

        </script>

      </head>
      <body>
      <h1>Game Search</h1>
      <input id="game" type="text" /><button id="search">Search</button>
      <div id="myelement"></div>
      </body>
    </html>

1 个答案:

答案 0 :(得分:7)

根据巨型炸弹文档标准的工作代码:

var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";

// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";

$(document).ready(function() {

  // send off the query
  $.ajax({
    url: GamesSearchUrl + '&query=' + encodeURI(query),
    dataType: "json",
    success: searchCallback
  });


    // callback for when we get back the results
    function searchCallback(data) {
        $('body').append('Found ' + data.total + ' results for ' + query);
        var games = data.game;
        $.each(games, function(index, game) {
            $('body').append('<h1>' + game.name + '</h1>');
            $('body').append('<p>' + game.description + '</p>');
            $('body').append('<img src="' + game.posters.thumbnail + '" />');
        });
    }
});

http://jsfiddle.net/LGqD3/

GiantBomb Api示例/解释

首先获取api密钥

重点:http://www.giantbomb.com/api/
文档:http://www.giantbomb.com/api/documentation

您的基本网址:

http://www.giantbomb.com/api/

您的网址结构:

/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS

  • /RESOURCE/ID示例:/ game / 3030-38206 /
    要返回的资源类型,在您的情况下是搜索。有时..如果是特定游戏,您还想传递/ID下的ID(如示例中所示)

  • api_key
    你的api密钥
    你需要这个,否则就不能使用api:)

  • format
    要输出的格式,在本例中为json。

  • FILTERS示例:/ search?limit = 100
    这操纵资源输出
    请参阅文档中的资源,了解您可以执行的操作。

  • FIELDS示例:/ search?field_list = description,
    要返回哪个字段,使用此字段来减少响应有效负载的大小&#34;

游戏请求它的名称&amp;描述将是:

http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description

搜索请求

让我们说我们想要搜索游戏&#34; Elder在线滚动&#34;。
你会像这样构建你的网址:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game

使用$ .ajax实现此功能:

ajax函数

/*
 *  Send a get request to the Giant bomb api.
 *  @param string resource set the RESOURCE.
 *  @param object data specifiy any filters or fields.
 *  @param object callbacks specify any custom callbacks.
 */
function sendRequest(resource, data, callbacks) {
    var baseURL = 'http://giantbomb.com/api';
    var apiKey = '[YOUR-API-KEY]';
    var format = 'json';

    // make sure data is an empty object if its not defined.
    data = data || {};

    // Proccess the data, the ajax function escapes any characters like ,
    // So we need to send the data with the "url:"
    var str, tmpArray = [], filters;
    $.each(data, function(key, value) {
        str = key + '=' + value;
        tmpArray.push(str);
    });

    // Create the filters if there were any, else it's an empty string.
    filters =  (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';

    // Create the request url.
    var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;

    // Set custom callbacks if there are any, otherwise use the default onces.
    // Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it. 
    // If not "||"" set an default function.
    var callbacks = callbacks || {};
    callbacks.beforeSend = callbacks.beforeSend || function(response) {};
    callbacks.success = callbacks.success || function(response) {};
    callbacks.error = callbacks.error || function(response) {};
    callbacks.complete = callbacks.complete || function(response) {};

    // the actual ajax request
    $.ajax({
        url: requestURL,
        method: 'GET',
        dataType: 'json',

        // Callback methods,
        beforeSend: function() {
            callbacks.beforeSend()
        },
        success: function(response) {
            callbacks.success(response);
        },
        error: function(response) {
            callbacks.error(response);
        },
        complete: function() {
            callbacks.complete();
        }
    });
}

搜索功能

function search() {
    // Get your text box input, something like: 
    // You might want to put a validate and sanitation function before sending this to the ajax function.
    var searchString = $('.textox').val();

    // Set the fields or filters 
    var data = {
        query: searchString,
        resources: 'game'
    };

    // Send the ajax request with to '/search' resource and with custom callbacks
    sendRequest('/search', data, { 
        // Custom callbacks, define here what you want the search callbacks to do when fired.
        beforeSend: function(data) {},
        success: function(data) {},
        error: function(data) {},
        complete: function(data) {},
    });
}

获取游戏功能的示例

function getGame() {
    // get game id from somewhere like a link.
    var gameID = '3030-38206';
    var resource = '/game/' + gameID;

    // Set the fields or filters 
    var data = {
        field_list: 'name,description'
    };

    // No custom callbacks defined here, just use the default onces.
    sendRequest(resource, data);
}

编辑:你也可以制作一个mini api包装器,例如:

var apiWrapper = {};

apiWrapper.request = function(resource, data, callbacks) {
    // The get function;
};

apiWrapper.search = function(data) {
    // The search function
};

apiWrapper.getGame = function(id, data) {
    // The game function
}

apiWrapper.init = function(config) {
    var config = config || {};
    this.apiKey = config.apiKey || false;
    this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}

apiWrapper.init({
    apiKey: '[API-KEY]'
});

没有测试过代码,因此可能存在错误,将它清理干净:) 编辑:修复$ .ajax中的错误