本文介绍了jsonp回调错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用firefox addon生成器。使用回调未定义运行此代码错误

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"
});

这是api文档:

推荐答案

我假设你是从内容脚本运行这个。您必须考虑内容脚本并不真正在与网页脚本相同的上下文中运行 - 网页无法查看内容脚本定义的函数,反之亦然()。 JSONP通过在网页中插入< script> 标记来工作。此脚本将在网页的上下文中运行 - 它不会显示您在内容脚本中定义的回调函数。

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.

要定义 callback 函数在窗口上下文中:

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

然后,您可以将 response.json 您的内容脚本通过。

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

这篇关于jsonp回调错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:55