使用Wikipedia的API从搜索查询中获取结果

时间:2022-08-22 10:32:29

I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :

我正在尝试使用Wikipedia的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>');
       }
   }

}
}); 

So far nothing appends to my html and there's no errors in my console.

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

4 个解决方案

#1


5  

@Ali Mamedov's answer is the way to go (it's from Wikipedia) But the wikipedia link is missing the http:. Also, you can handle the response on your function:

@Ali Mamedov的答案是去的路(它来自*),但是*链接没有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>');
     }
  }

#2


2  

        $.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>

Source

#3


1  

Try this sample:

试试这个示例:

$(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

#4


1  

This will show the query result with image:

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

$(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);
     }      
  });
 });
}); 

#1


5  

@Ali Mamedov's answer is the way to go (it's from Wikipedia) But the wikipedia link is missing the http:. Also, you can handle the response on your function:

@Ali Mamedov的答案是去的路(它来自*),但是*链接没有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>');
     }
  }

#2


2  

        $.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>

Source

#3


1  

Try this sample:

试试这个示例:

$(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

#4


1  

This will show the query result with image:

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

$(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);
     }      
  });
 });
});