JSONP请求错误

时间:2016-01-08 03:50:52

标签: javascript json

我试图向此网址发出请求:

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.

...在控制台中。我该如何执行此请求?感谢!!!

1 个答案:

答案 0 :(得分:4)

尝试将src网址更改为以下内容:

https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=json&callback=foo

这会导致API发送您正在寻找的相应JSONP响应。

编辑 - 现在有了正常工作的代码。

&#13;
&#13;
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;
&#13;
&#13;