简体   繁体   中英

Unable to get data from Wikipedia API

I am working on a 'Wikipedia Viewer' project, where you enter a search term and see a list of Wikipedia search results, but it is .

Until now I have just written the code to display the first search term. But it doesn't work.

My HTML:

 <div class="container-fluid"> <div class="searchAndButtons"> <input type="text" id="search"> <button class="btn" id="searchBut">Search</button> <form action="https://en.wikipedia.org/wiki/Special:Random"><button class="btn">Random Wiki Article</button> </form> </div> <div class="searchResults"> </div> </div> 

My CSS:

 .container-fluid{ padding:5%; } .searchAndButtons{ text-align:center; } 

My Javascript:

 $(document).ready(function(){ $("#searchBut").on("click",function(){//this is click handler var searchTerm=document.getElementById("#search").value; searchTerm=searchTerm.replace(/\\s/g,"+"); $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){ $(".searchResults").html(JSON.stringify(json)); }); }); }); 

Where am I going wrong? When I run the code in Codepen and check the console, it shows an error "TypeError: document.getElementById(...) is null". My project on codepen - link

$(document).ready(function(){
  $("#searchBut").on("click",function(){//this is click handler
   var searchTerm=document.getElementById("search").value;
    searchTerm=searchTerm.replace(/\s/g,"+");

    $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
       $(".searchResults").html(JSON.stringify(json));

        });
    });
  });

Update your JS code with this. id gets value by 'search' not '#search'

UPDATE : To add headers you can do the following

 $(document).ready(function(){
      $("#searchBut").on("click",function(){//this is click handler
       var searchTerm=document.getElementById("search").value;
        searchTerm=searchTerm.replace(/\s/g,"+");



    $.ajax({
              url: 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1', //your request URL
              type: 'GET',
              dataType: 'json',
              success: function() { alert('hello!'); },
              error: function() { alert('boo!'); },
              beforeSend: setHeader
            });
          });

          function setHeader(xhr) {
            xhr.setRequestHeader('securityCode', 'Foo'); //your header key and value
          }

        });
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM