I'm new to java-script,I'm trying to use wikipedia api
to build a simple demo to show the results of what I typed.When I use jQuery $.get() to access json data,before the data returns and the code goes on(because the $.get() works Asynchronously I think?),and the dataArr haven't catch any data yet, so I cannot add my query results to the pages.The js code goes below:
function getData(queryStr) {
var dataArr = [];
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&origin=*&gsrsearch=';
var addr = url + queryStr;
$.get(addr, function (data) {
console.log(data.query.pages);
for (var key in data.query.pages) {
dataArr.push(data.query.pages[key]);
}
});
dataArr.forEach(function (elem, index) {
if (index == 10) {
return;
}
//var pageid = elem.pageid;
var title = "<h2 class='title'>" + elem.title + "</h2>";
var extract = '<p class="extract">' + elem.extract + '</p>';
var resultDiv = '<div class="searchResults">' + title + abstract + '</div>';
$(".showResultes").append(resultDiv);
})
};
function prepareBtn() {
var queryResult = [];
$(".searchBtn").click(function () {
var queryStr = "";
if ($("#queryStr").val()) {
queryStr = $("#queryStr").val();
$(".showResultes").empty();
getData(queryStr);
} else {
alert("please input something!");
return;
}
});
}
window.onload = prepareBtn();
The html code goes here:
<div class="form-inline text-center inputSearch">
<img src="https://en.wikipedia.org/static/images/project-logos/enwiki-2x.png">
<input type="text" class="form-control" id="queryStr"
placeholder="plz input"> <button class="btn btn-primary searchBtn">search</button>
</div>
<div class="showResultes">
</div>
Again,I'm new to the web development,if there is any advice about other issues in my code,I be very thankful. `