.getJSON 即使 URL 有效也不会成功

.getJSON won't succeed even though URL works

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 根本行不通。

能否记录下成功和失败的方法。可能存在 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" );
}); 

您需要做的就是向您的按钮单击事件添加一个 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);
            }
        });
    });
});