0

I'm trying to construct a simple jQuery function that fetches JSON data from a URL but I can't seem to get any output. Can anyone tell me where I'm going wrong?

<button id="test">Test</button>
$(document).ready(function() {
    $("#test").click(function() {  
        $.getJSON('https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json', function(objDATA) {
            document.write(objDATA);
            console.log(objDATA);
        });
    });                            
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Uesls
  • 101
  • 6
  • 2
    CORS issue see the error `XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'example.com' is therefore not allowed access.` – Satpal Mar 17 '16 at 09:11
  • try to not use `document.write` and then, you'll not be able to retrieve the JSON because of the CORS, if the url requested is not the same as the current domain, and it does not accept cross origin request. – Hacketo Mar 17 '16 at 09:11

1 Answers1

0

It's likely access control / allow-origin thats tripping you up here. Look up "No 'Access-Control-Allow-Origin'"

This works:

$('#test').on('click', function()
{
    $.getJSON('https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json&callback=?', function(data)
    {
        console.log(data);
    });
});

Notice the addition of &callback=?

Stuart
  • 6,630
  • 2
  • 24
  • 40