HTML
<body>
<header>
<div class="container-fluid">
<h1>Wikipedia Viewer</h1>
<form id="userInput">
<input id="query" type="text" name="userInput" value="" placeholder="Search">
<input id="submitBtn" type="submit" name="send" value="Click!">
</form>
<a id="randomArticle" href="https://en.wikipedia.org/wiki/Special:Random"><i class="fa fa-random fa-2x" aria-hidden="true"></i></a>
</div>
</header>
<div class="results">
</div>
</body>
</html>
的Javascript
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&callback=?&search=";
var userQuery = "";
var html = "";
$(document).ready(function () {
$("#userInput").submit(function (e) {
userQuery = document.getElementById("query").value;
$.getJSON(url + userQuery, function (data) {
for (var i = 0; i < data[1].length; i++) {
html = '<article><a href="' + data[3][i] + '"target="_blank"><h3>' + data[1][i] + '</h3><p>' + data[2][i] + '</p></a></article>';
$(".results").append(html);
}
});
});
});
当我到达.getJSON时它就不会成功,我已经测试了URL并且JSON出现在浏览器中,但使用Jquery的请求将无效。
答案 0 :(得分:2)
您需要做的就是在按钮点击事件中添加jQuery preventDefault()
方法,如下所示:
$(document).ready(function () {
$("#userInput").submit(function (e) {
e.preventDefault();
userQuery = document.getElementById("query").value;
$.getJSON(url + userQuery, function (data) {
for (var i = 0; i < data[1].length; i++) {
html = '<article><a href="' + data[3][i] + '" target="_blank"><h3>' + data[1][i] + '</h3><p>' + data[2][i] + '</p></a></article>';
$(".results").append(html);
}
});
});
});
答案 1 :(得分:0)
您可以记录成功和失败方法吗?可能会出现Cross Origin
问题,如果是这样,那么您需要在服务器级别添加cors。
您可以按照http://api.jquery.com/jquery.getjson/
所述记录成功与失败// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});