0
我正在“维基百科查看器”项目上工作,您在此输入搜索词并查看维基百科搜索结果列表,但它的编号为远不是完整。无法从维基百科获取数据API
到现在为止,我刚才编写了代码来显示第一个搜索项。但它不起作用。
我的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>
我的CSS:
.container-fluid{
padding:5%;
}
.searchAndButtons{
text-align:center;
}
我的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));
});
});
});
我要去哪里错了?当我在Codepen中运行代码并检查控制台时,它显示“TypeError:document.getElementById(...)为null”的错误。 我的项目上codepen - link
感谢您的帮助,但它仍然无法正常工作。现在,我在控制台中收到一个新错误 - “跨源请求被阻止:同源策略不允许通过https://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=c&rvprop读取远程资源= content&format = json&rvsection = 0&rvparse = 1。(原因:缺少CORS头'Access-Control-Allow-Origin')。“ – aks
@aks已更新我的答案。检查出来的标题,你可以试试'Access-Control-Allow-Origin:http:// foo.example'作为键和值 – Smit
这段代码是getJSON函数的替代品吗?或者我应该将此代码添加到我的getJSON?对不起,如果这个问题似乎很愚蠢,但我是一个初学者。 – aks