如何显示维基百科搜索

How display Wikipedia search?

本文关键字:百科 搜索 显示 何显示      更新时间:2023-09-26

我最近刚开始用JavaScript编程,我必须使用wikimedia API创建自己的维基百科页面,但不明白当点击搜索时如何从文本框中提取数据并显示结果。

<!DOCTYPE html>
<html>
<body>
<h1>Wikipedia</h1>
<div id="search1" />
<input type="text" name="search" /></b>
<button id="s1">search</button>
</div>
<p id="display"></p>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://community-wikipedia.p.mashape.com/api.php" ;
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
var key = "oCdV3MjLj1mshtyIXwBVzBqRKtY9p1XJNiajsn1vsCETYVLwK3";
req.setRequestHeader("X-Mashape-Key", key);
xmlhttp.send();
function Function(response) {
 var a = JSON.parse(response);
 var i;
 text = "";
 for(i = 0; i < a.length; i++) {
     text += a[i]+ "<br>";
 }
document.getElementById("search1").addEventListener("click",displaysearch);
function displaysearch(){
//display search items here
}

}
</script>
</body>
</html>

您可以在html中使用iframe,在单击搜索按钮后进行设置,也可以使用jQuery ajax GET调用,向您访问的维基百科页面发送调用请求,如果成功,则返回相应的数据。

 $.ajax({
    url: '/path/to/file',
    type: 'default GET (Other values: POST)',
    dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
    data: {param1: 'value1'},
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

jQuery可能是两者中更好的选择。(在我看来)

另一种选择是使用iFrames(javascript):

var ifrm = document.createElement('iframe');
ifrm.setAttribute('id', 'ifrm');
ifrm.setAttribute('src', 'demo.html'); //URL can go here
document.body.appendChild(ifrm); //places iFrame at the end of the page