Dart JSONP回调错误

Dart JSONP callback error

本文关键字:错误 回调 JSONP Dart      更新时间:2023-09-26

我目前正在尝试使用JSONP接收数据。当我击中https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=巴拉克%20obama;callback=回调JsonpApi

我得到的回复非常好:

callbackForJsonpApi({RESPONSE HERE})

但当我去https://api.forecast.io/forecast/APIKEYHERE/37.8267,-122.423?callback=callbackforJsonApi我得到:

typeof callbackforJsonApi === 'function' && callbackforJsonApi({ RESPONSE HERE})

有人能解释为什么我在一个回答前准备了"类型"的部分,而在另一个回答后没有?

这是我的网站艺术文件:

void main() {
  // listen for the postMessage from the main page
  window.onMessage.listen(dataReceived);
  ScriptElement script = new Element.tag("script");
  script.src = "https://api.forecast.io/forecast/APIKEY/37.8267,-122.423?callback=callbackforJsonApi";
  document.body.children.add(script);
}
dataReceived(MessageEvent dataReceived) {
  var data = JSON.parse(dataReceived.data);
  print(data['responseData']);
}

这是我的部分html:

<html>
    <body>
        <script type="text/javascript">
          function callbackForJsonpApi(s) {
            var data = JSON.stringify(s);
            window.postMessage(data, '*');
          }
    </body>
</html>

我无法解释为什么这些不同;谷歌方面似乎有点疏忽(大概他们应该是一样的)。

两者均有效;但有额外支票的看起来最好;它只是试图在函数存在(并且是一个函数)的情况下调用它;如果您没有声明函数,它将停止JavaScript错误。

如果您在服务器端执行此操作,并将代码吐入页面;您可能应该尝试让您的代码同时容忍这两种情况;以防你将来碰巧有不同的行为(例如,如果谷歌让这些行为保持一致)。