使用维基百科的 API 从搜索查询中获取结果

Using Wikipedia's API to fetch results from search query

我正在尝试使用维基百科的 API 进行搜索查询,然后将这些结果附加到我的页面。这是我目前所拥有的:

 "use strict";
$(document).ready(function(){

function searchWikipedia(searchCriteria){
    $.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);

}


$('#btn').click(function searchCriteria() {
    var searchCriteria = $("input[name=Wikipedia]").val();
    searchWikipedia(searchCriteria);

})

function processResult(apiResult){

  if (apiResult.query.pages[-1]){
       console.log("No results");
    } else {
       for (var i = 0; i < apiResult.length; i++){
             $('#display-result').append('<p>'+apiResult+'</p>');
       }
   }

}
}); 

到目前为止,我的 html 没有任何附加内容,我的控制台中也没有任何错误。

试试这个示例:

$(document).ready(function(){

    $('#btn').click(function() {

        $.ajax({
            url: '//en.wikipedia.org/w/api.php',
            data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
            dataType: 'jsonp',
            success: function (x) {
                console.log('title', x.query.search[0].title);
            }
        });
    });
}); 

Source

@Ali Mamedov 的回答是要走的路(来自维基百科) 但是维基百科 link 缺少 http:。此外,您可以处理函数的响应:

   $(document).ready(function(){
        $('#btn').click(function() {
            $.ajax({
                url: 'http://en.wikipedia.org/w/api.php',
                data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
                dataType: 'jsonp',
                success: processResult
            });
        });
    }); 

  function processResult(apiResult){
     for (var i = 0; i < apiResult.query.search.length; i++){
          $('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
     }
  }
 <script type="text/javascript">
               

            $.ajax({
                type: "GET",
                url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
                contentType: "application/json; charset=utf-8",
                async: false,
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    $.each(data, function (i, item) {
                        if (i == 1) {
                            var searchData = item[0];
                            WikipediaAPIGetContent(searchData);
                        }
                    });
                },
                error: function (errorMessage) {
                    alert(errorMessage);
                }
            });
        }

        function WikipediaAPIGetContent(search) {
            $.ajax({
                type: "GET",
                url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=" + search + "&callback=?",
                contentType: "application/json; charset=utf-8",
                async: false,
                dataType: "json",
                success: function (data, textStatus, jqXHR) {

                    var markup = data.parse.text["*"];
                    var blurb = $('<div></div>').html(markup);

                    // remove links as they will not work
                    blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });

                    // remove any references
                    blurb.find('sup').remove();

                    // remove cite error
                    blurb.find('.mw-ext-cite-error').remove();
                    $('#results').html($(blurb).find('p'));
                    $('#results').html(blurb);

                },
                error: function (errorMessage) {
                    alert(errorMessage);
                }
            });
        }
    </script>

这将显示带有图像的查询结果:

$(document).ready(function(){
  $('#btn').click(function() {
     var search_text = $("input[name=Wikipedia]").val();
     var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
     $.getJSON( url + search_text +'&callback=?',function(data){        
      for(var key in data.query.pages){
        var titleArt = data.query.pages[key].title;
        var extractArt = data.query.pages[key].extract;
        var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
        var imgArt;

        if(data.query.pages[key].hasOwnProperty('thumbnail')){
          imgArt = data.query.pages[key].thumbnail.source;
        } else {
          imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
        }

        var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><a href="' +  linkArt + '" target="_blank"><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></a></div></div>';
        $('#display-result').append(contentHTML);
     }      
  });
 });
}); 

function Wiki(lang) {
  this.lang = lang || "fr";
  this.inuse = false;
}

Wiki.prototype.research = function(s, callback) {
  if (this.inuse) {
    console.error("Wiki est déjà en cours d'utilisation !");
  } else {
    this.inuse = true;
    var r = new XMLHttpRequest();
    r.onload = function() {
      Wiki.prototype.inuse = false;
      var j = JSON.parse(r.responseText);
      callback(j);
    }
    r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
    r.send();
  }
}

var c = new Wiki();
c.research("Victor Hugo", function(result) {
  console.log(result);
});

//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
  console.log(result);
}