【问题标题】:JSONP not working on the pageJSONP 在页面上不起作用
【发布时间】:2011-10-14 07:59:46
【问题描述】:

我有一个使用wikipedia api 的页面。但是由于我不能使用JSON 进行跨域限制,所以我使用JSONP。我的代码是这样的

<body>
<script type="text/javascript">
function res(data){
  alert(data);
};
</script>
<script type="text/javascript" src="http://en.wikipedia.org/w/api.php?action=opensearch&search=api&callback=res&limit=10&namespace=0&format=jsonfm">
</script>
</body>

这里我在 url 中提供名为 res 的回调函数。正如我在萤火虫中看到的那样,响应来了

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MediaWiki API Result</title>
</head>
<body>
<br />
<small>
You are looking at the HTML representation of the JSON format.<br />
HTML is good for debugging, but probably is not suitable for your application.<br />
See <a href='http://www.mediawiki.org/wiki/API'>complete documentation</a>, or
<a href='/w/api.php'>API help</a> for more information.
</small>
<pre>
res([
&quot;api&quot;,
[
&quot;API&quot;,
&quot;Apiales&quot;,
&quot;Apiaceae&quot;,
&quot;Apia&quot;,
&quot;Apicomplexa&quot;,
&quot;Apicomplexa lifecycle stages&quot;,
&quot;Apidae&quot;,
&quot;APIA Leichhardt Tigers&quot;,
&quot;Apical membrane&quot;,
&quot;Apical consonant&quot;
]
])
</pre>
</body>
</html> 

这意味着服务器正在发送包含在回调函数res中的响应,但是浏览器没有执行这个函数(alert没有被调用)。我使用的是firefox 5。这有什么问题?

【问题讨论】:

    标签: callback jsonp wikipedia-api


    【解决方案1】:

    它在回复中说:

    您正在查看 JSON 格式的 HTML 表示。
    HTML 适合调试,但可能不适合您的 应用程序。

    试试

    <script type="text/javascript" src="http://en.wikipedia.org/w/api.php?action=opensearch&search=api&callback=res&limit=10&namespace=0&format=json">
    

    【讨论】:

    • 那么我如何获得json 格式。我在 url 中将 format 参数作为 json 传递。
    • 你正在传递 jsonfm。试试我发布的内容。它应该可以工作。
    • 那行得通。在他们指定为jsonfm 的维基百科 api 文档中很好,所以我认为这意味着 json 格式。你能告诉他们为什么说它是 jsonfm。这是[链接](www.mediawiki.org/wiki/API:Data_formats)
    • 真的很奇怪...他们提供的示例使用jsonfm...不知道。
    • 看看这个页面,你应该在那里找到答案:en.wikipedia.org/w/api.php
    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    相关资源
    最近更新 更多