简体   繁体   中英

Why .getjson doesnt work but .ajax does?

I'm working on Free Code Camp's wiki viewer and trying to figure out the api call. I thought getjson and ajax were equivalent but maybe i'm doing something wrong.

So at first I used this getjson code:

$.getJSON('http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=' + search, 
function(api){
    console.log(api);
}, 'jsonp');

but it returned this error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Then I used ajax with the same url:

$.ajax({
      url: 'http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=' + search,
      dataType: 'jsonp',
      success: getWiki //just console logs the api
            });

and this seemed to return the api call. Can anyone explain why getjson didnt work but ajax did?

You're missing the required callback=? query parameter to force $.getJSON to perform a JSONP request

$.getJSON('http://en.wikipedia.org/w/api.php?callback=?', {
  action: 'query',
  list: 'search',
  format: 'json',
  srsearch: search
}, api => {
  // response handler
})

See http://api.jquery.com/jquery.getjson/#jsonp

This is my solution also I left an alternative using only JavaScript

NOTE I added this &origin=* param in the url to make it work using this the original jQuery code.

 var search = 'php'; var searchURL = 'https://en.wikipedia.org/w/api.php?action=query&format=json&generator=search&origin=*&gsrsearch=' + search; // Using JSON $.getJSON(searchURL, function(data){ var read = JSON.stringify(data); console.log('Using jQuery: ' + read); }, 'jsonp'); // Using JavaScript var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function() { var status = xhr.status; if (status == 200) { callback(null, xhr.response); } else { callback(status); } }; xhr.send(); }; getJSON(searchURL, function(err, data) { if (err != null) { alert('Something went wrong: ' + err); } else { var read = JSON.stringify(data); console.log('Using JavaScript: ', read); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM