问题
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