【问题标题】:Access Wikipedia API JSON data in jQuery在 jQuery 中访问 Wikipedia API JSON 数据
【发布时间】:2017-05-10 03:12:28
【问题描述】:

$('#searchButton').click(function(){
  var searchInput = "";
  searchInput = document.getElementById('test');
  if(searchInput.value !== ""){
    $.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch='+searchInput+'&utf8=', function(json){
      alert(json.query.search[0].title);
    });
  }
});

我很困惑为什么 Json 似乎没有加载到页面中。似乎整个操作在 url 处停止,即使我在警报中输入了一个字符串,它也不会运行......

【问题讨论】:

  • 可能是 CORS。您在控制台上看到任何消息了吗?
  • 这是我在控制台上收到的消息 index.html:1 XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=[object%20HTMLInputElement]&utf8=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access. 我不太清楚这一切意味着什么,但感谢您的帮助,我肯定会弄明白的。
  • 改用 JSONP

标签: javascript jquery json mediawiki


【解决方案1】:

您收到此错误是因为没有为您调用mediawiki 的来源启用CORS,您可以在此处查看更多信息。

https://www.mediawiki.org/wiki/Manual:CORS

您可以将jQuery jsonp 请求与dataType: 'jsonp' 一起使用,如下所示。

工作sn-p:

$(document).ready(function() {

$('#searchButton').click(function(){
  var searchInput = "";
  searchInput = document.getElementById('test');
  if(searchInput.value !== ""){
    
    $.ajax( {
    url: 'https://en.wikipedia.org/w/api.php',
    data: {
        action: 'query',
        list: 'search',
        format: 'json',
        srsearch: searchInput.value
    },
    dataType: 'jsonp'
} ).done( function ( json ) {
    alert(json.query.search[0].title);
} );
    
  }
});
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />
<input type="button" id="searchButton" value="Search" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2014-07-25
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    相关资源
    最近更新 更多