为什么我的Wikipedia API搜索不起作用?

时间:2019-01-04 20:51:20

标签: javascript html api

我的Wikipedia API搜索脚本收到此错误消息:

script.js:76 Uncaught TypeError: Cannot read property 'addEventListener' of null
at script.js:76
at script.js:101 

它应该显示Wikipedia的结果,但是没有回应。

script.js:

"use strict"
//JS for Wikipedia API
  (function(){
// creates a new object called xhr
// which will handle the API call
let xhr = new XMLHttpRequest();     
// console.log(`Current readyState: 
${xhr.readyState}`);
let queryBox = 
document.getElementById("wikiQuery");
let searchForm = 
document.getElementById("searchForm");
let demoJSON = 
document.getElementById("demo");

// constructs the base for the request url
let baseURL = 
"https://en.wikipedia.org/w/api.php? \
format=json& \
action=query& \
generator=search& \
gsrnamespace=0& \
gsrlimit=10& \

prop=info|extracts|langlinks|pageimages& \
inprop=url& \
exintro& \
explaintext& \
exsentences=1& \
exlimit=max& \
llprop=url& \
lllimit=max& \
piprop=thumbnail|name& \
origin=*& \
gsrsearch=";

function gatherData(data) {
// console.log(data);
// initialise some variables
let theData = "";
let langLinks = "";
let img = "<img>";
const languages = ["en", "de", "zh", "fr", 
"es", "ja", "ar", "ko", "el"];
let k;
let key;
// loop through the result pages by pageid
for(key in data.query.pages) {
let tmp = data.query.pages[key];
if (tmp.thumbnail) {
img = `<img src="${tmp.thumbnail.source}" 
alt="${tmp.title}"> `;
}
let title = `<strong><a 
href="${tmp.fullurl}">${tmp.title}</a> 
</strong>`;
let extract = `<span 
class="txt">${tmp.extract}</span>`;
let langLinks = "";
for (k in tmp.langlinks) {
if

(languages.includes(tmp.langlinks[k].lang)
) 
{
langLinks += `<a 
href=${tmp.langlinks[k].url}>$
{tmp.langlinks[k].lang}</a> `;   
}
}
theData += `<li>${img} ${title} ${extract} 
<span class="langs">${langLinks}</span> 
</li>`;
      }
demoJSON.innerHTML = theData;
}

// the API call is triggered once the user 
submits a query
searchForm.addEventListener("submit", 
function(ev){
// complete the request url
let wiki = baseURL + queryBox.value;
// open a connection to the requested API 
url
xhr.open("GET", wiki, true);
// be polite to Wikipedia
xhr.setRequestHeader('Api-User-Agent', 
'Example/1.0');
// send off that request
xhr.send();
// if the response was ok, handle the 
response data using the gatherData 
function
xhr.onreadystatechange = function() {
// console.log(`Current 
readyState: ${xhr.readyState}`);
if (xhr.readyState === 4 && xhr.status === 
200) {
// parse the response JSON
let response = 
JSON.parse(xhr.responseText);
// deal with the parsed JSON data
gatherData(response);
}
};
// clear the search box
queryBox.value = "";
ev.preventDefault();
}, false);
}());

1 个答案:

答案 0 :(得分:1)

您的脚本无法在指令id中找到带有document.getElementById("searchForm")“ searchForm”的元素。

确保它存在,没有键入并且您的脚本在创建后被称为