我试图向此网址发出请求:
https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=json
...使用JSONP。
我用来发出此请求的功能是
<script>
function foo(data)
{
var obj = JSON.parse(data);
console.log(obj);
}
var script = document.createElement('script');
script.src = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
</script>
当我在谷歌浏览器中加载此功能时,我得到了
Refused to execute script from 'https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=jsonp?callback=foo' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
...在控制台中。我该如何执行此请求?感谢!!!
答案 0 :(得分:4)
尝试将src网址更改为以下内容:
这会导致API发送您正在寻找的相应JSONP响应。
编辑 - 现在有了正常工作的代码。
function foo(data)
{
console.log(data[0]);
}
var script = document.createElement('script');
script.src = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=json&callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
&#13;