问题描述
我需要在Chrome扩展程序中执行跨域请求。我知道我可以通过,但我宁愿坚持只使用jQuery成语(所以我的javascript也可以作为< script src =>
)。
I做正常的:
$。getJSON(http://api.flickr.com/services/feeds/photos_public.gne ?tags = cat& tagmode = any& format = json& jsoncallback =?,function(data){
console.log(data);
});
但是在错误控制台中我看到:
未捕获的ReferenceError:未定义jsonp1271044791817
jQuery不是将回调函数正确插入文档中?我能做些什么来完成这项工作?
(如果我把代码粘贴到一个chrome控制台中,它可以正常工作,但是如果我把它作为page.js )
唉,这些都不起作用,所以我最终通过background.html。
background.html
< script src = http://code.jquery.com/jquery-1.4.2.js >< /脚本>
< script>
函数onRequest(request,sender,callback){
if(request.action =='getJSON'){
$ .getJSON(request.url,callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
< / script>
javascripts / page.js
chrome_getJSON = function(url,callback){
console.log(sending RPC);
chrome.extension.sendRequest({action:'getJSON',url:url},callback);
$(function(){
//使用chrome_getJSON而不是$ .getJSON
});
I need to do a cross-domain request in a chrome extension. I know I can it via message passing but I'd rather stick to just jQuery idioms (so my javascript can also work as a <script src="">
).
I do the normal:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
but in the error console I see:
Uncaught ReferenceError: jsonp1271044791817 is not defined
Is jQuery not inserting the callback function correctly into the document? What can I do to make this work?
(If I paste the code into a chrome console, it works fine, but if I put it as the page.js in an extension is when the problem appears.)
Alas, none of these worked, so I ended up doing the communication via the background.html.
background.html
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script>
function onRequest(request, sender, callback) {
if (request.action == 'getJSON') {
$.getJSON(request.url, callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
</script>
javascripts/page.js
chrome_getJSON = function(url, callback) {
console.log("sending RPC");
chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}
$(function(){
// use chrome_getJSON instead of $.getJSON
});
这篇关于在Chrome扩展中使用jQuery.getJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!