我想要做的(现在)是用搜索字符串查询Wikipedia API,
$(document).ready(function() {
$(".search").on("click", getArticles);
function getArticles() {
var searchTerm = $("#wiki-search").val().trim();
console.log(searchTerm);
var url = "http://en.wikipedia.org//w/api.php?callback=?";
$.getJSON(url, {
action: "query",
format: "json",
list: "search",
srprop: "snippet",
srlimit: 10,
srsearch: searchTerm
}, displayArticles);
并从返回的JSON对象中,通过将其附加到div元素来显示特定属性(在本例中为snippet
)的值:
function displayArticles(wikiJSON) {
if(wikiJSON.query.searchinfo.totalhits === 0) {
// resultsDiv.innerHTML = "No results found";
$("<h3>No results Found</h3>").appendTo("#resultsID");
}
else {
$(wikiJSON.query.search[0].snippet).appendTo("#resultsID");
}
但正如此pen所示,代码段值会在屏幕上暂时闪现并消失。有谁能解释我的代码出了什么问题?
HTML:
<form role="form">
<div class="input-group">
<input class="form-control" id="wiki-search" type="text" placeholder="Enter search string...">
<span class="input-group-btn">
<button class = "btn btn-default search">
<i class = "glyphicon glyphicon-search"></i>
</button>
</span>
<span class="input-group-btn">
<button class = "btn btn-default random">
<i class = "glyphicon glyphicon-random"></i>
</button>
</span>
</div>
</form>
<div class= "row result-group">
<div class = "col-xs-12 col-sm-8 col-sm-offest-2 col-md-6 col-md-offset-3">
<div class = "results" id = "resultsID">
</div>
答案 0 :(得分:2)
有两个问题。
首先,您的button is implicitly submitting the form(其默认类型为submit
)。
因此,您需要将type="button"
添加到button
个元素中。
其次,返回的html无法发送到jQuery构造函数,因为根据jQuery构造函数,它在语法上不正确。有一条记录的错误消息:“未捕获错误:语法错误,无法识别的表达式”。结果应发送到.html()
函数。
$("<div>").html(wikiJSON.query.search[0].snippet).appendTo("#resultsID")