wikipedia API JSON isn't recognized by $.getJS

2019-07-12 10:56发布

问题:

I know already that this method works for other JSON formatted data but not the wikipedia API JSON output as listed here. Any help would be great:

$.getJSON('https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=starwars', function(data) {
    $("p").html(JSON.stringify(data));
});

回答1:

Add callback

$.getJSON('https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=starwars&callback=?', function(data) {
    console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



回答2:

Another way is to $.ajax with a jsonp dataType:

jQuery(document).ready(function($) {
  $.ajax({
    url: "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=starwars",
    dataType: "jsonp",
    success: function(data) {
      $("pre").html(JSON.stringify(data, null, 3));
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>



回答3:

Jaromanda X is right, you'll need to use a callback function to sort this out. https://www.mediawiki.org/wiki/API:Cross-site_requests/en