jsonp callback error

感情迁移 提交于 2019-12-23 12:19:26

问题


I'm using firefox addon builder. Running this code errors with "callback is not defined"

function callback(data) {
   window.alert(data.status);
}

$.ajax({
   url: "http://apps.compete.com/sites/google.com/trended/rank/?apikey=210e634a0b3af972daa908a447c735c1&start_date=201112&end_date=201112&jsonp=?",
   dataType: "jsonp",
   jsonp: "jsonp",
   jsonpCallback: "callback"
});

This is the api documentation: https://www.compete.com/developer/documentation/


回答1:


I'm assuming that you are running this from a content script. You have to consider that content scripts don't really run in the same context as the web page's scripts - the web page cannot see functions defined by content scripts and vice versa (detailed description of this mechanism). JSONP works by inserting a <script> tag into the web page. This script will run in the context of the web page - and it won't see the callback function you defined in the content script.

To define the callback function in the window context you do:

unsafeWindow.callback = function(data)
{
  window.alert(data.status);
};

However, you should take the warnings about unsafeWindow in the documentation seriously and avoid it if possible. Use the request package in your extension to load the data:

require("request").Request({
  url: "http://apps.compete.com/sites/google.com/trended/rank/?apikey=210e634a0b3af972daa908a447c735c1&start_date=201112&end_date=201112",
  onComplete: function(response)
  {
    console.log(response.json);
  }
});

You can then send response.json to your content script via usual messaging.




回答2:


Try this.

$.ajax({
     url: "http://apps.compete.com/sites/google.com/trended/rank/?apikey=210e634a0b3af972daa908a447c735c1&start_date=201112&end_date=201112&jsonp=?",
     dataType: "jsonp",
     success: function(data) {
         window.alert(data.status);
    }
});



回答3:


You should not append jsonp=? to your url, this is done by the ajax function.

Use only:

url: "http://apps.compete.com/sites/google.com/trended/rank/?apikey=<your-api-key>&start_date=201112&end_date=201112",



回答4:


Actually, in response to Marcelo Diniz, and anyone trying to get the compete API working:
You need &jsonp=? appended to your url or else your ajax request will always fail.

I struggled with this for a while because the docs from compete were vague.



来源:https://stackoverflow.com/questions/8961091/jsonp-callback-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!