简体   繁体   English

Dart JSONP回调错误

[英]Dart JSONP callback error

I am currently trying to receive data using JSONP. 我目前正在尝试使用JSONP接收数据。 When I hit https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=barack%20obama&callback=callbackForJsonpApi 当我点击https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=barack%20obama&callback=callbackForJsonpApi

I get the response perfectly fine: 我得到的响应非常好:

callbackForJsonpApi({RESPONSE HERE})

But when I go to https://api.forecast.io/forecast/APIKEYHERE/37.8267,-122.423?callback=callbackforJsonApi I get: 但是当我转到https://api.forecast.io/forecast/APIKEYHERE/37.8267,-122.423?callback=callbackforJsonApi时,我得到:

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

Can anyone explain why I have that "typeof" part prepended to one response but not the other? 谁能解释为什么我的“ typeof”部分位于一个响应的前面,而没有另一个?

This is my site.dart file: 这是我的site.dart文件:

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']);
}

This is my partial html: 这是我的部分html:

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

I can't explain why these are different; 我无法解释为什么它们不同。 seems like a bit of an oversight on Google's part (presumably they should be the same). Google似乎有点疏忽大意(大概他们应该是相同的)。

Both of them are valid; 他们两个都是有效的。 but the one with the extra check looks best; 但是带有额外支票的那张看起来最好; it's only trying to call the function if it exists (and is a function); 它只会尝试调用该函数(如果存在)(并且是一个函数); which will stop a JavaScript error if you haven't declared the function. 如果您尚未声明该函数,则会停止JavaScript错误。

If you're pulling this in server-side and spitting the code into your page; 如果要在服务器端进行处理,然后将代码吐到页面中; you should probably try and make your code tolerate both of these; 您可能应该尝试使您的代码同时容忍这两个方面; just in case you happen to get different behaviour in the future (eg. if Google make these consistent). 以防万一您将来会遇到不同的行为(例如,如果Google保持一致)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM