繁体   English   中英

为什么.getjson不起作用而.ajax起作用?

[英]Why .getjson doesnt work but .ajax does?

我正在研究Free Code Camp的Wiki查看器,并试图找出api调用。 我以为getjson和ajax是等效的,但也许我做错了。

因此,起初我使用了以下getjson代码:

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

但它返回此错误: 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.

然后,我使用了具有相同网址的ajax:

$.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
            });

这似乎返回了api调用。 谁能解释为什么getjson不起作用而ajax起作用了?

您缺少必需的callback=? 查询参数强制$.getJSON执行JSONP请求

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

参见http://api.jquery.com/jquery.getjson/#jsonp

这是我的解决方案,我只使用JavaScript留下了替代方案

注意我在URL中添加了此&origin=*参数,以使其使用此原始jQuery代码工作。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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