在 Google Chrome 扩展中使用 jQuery.ajax
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6800988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery.ajax in a Google Chrome extension
提问by Minh Nguyen
I use jquery.ajax function to post data from google chrome extension to my web service as code below:
我使用 jquery.ajax 函数将数据从 google chrome 扩展发布到我的网络服务,代码如下:
$.ajax({
type: "POST",
url: serviceUrl,
data: data,
success: function(msg){
if(typeof(Me.config.onSumitted) == "function"){
Me.config.onSumitted(msg);
}
},
error: function(){
if(typeof(Me.config.onError) == "function"){
Me.config.onError();
}
}
});
but i get an error:
但我收到一个错误:
XMLHttpRequest cannot load http://todomain.com/Service.asp. Origin http://fromtabdomain.com is not allowed by Access-Control-Allow-Origin.
how can i resolve it?
我该如何解决?
回答by ChristopheCVB
You can have a look at this page to achieve what you want :
您可以查看此页面以实现您想要的:
http://code.google.com/chrome/extensions/xhr.html
http://code.google.com/chrome/extensions/xhr.html
It is just about setting permissions...
这只是关于设置权限...
回答by Gev
you need to add a permission to you manifest.js file
您需要为 manifest.js 文件添加权限
"permissions": [
"http://www.yourwebsite.com/"
],
回答by MarioW
As @ChristopheCVB pointed out http://code.google.com/chrome/extensions/xhr.htmltells you what to do:
正如@ChristopheCVB 指出的,http: //code.google.com/chrome/extensions/xhr.html告诉你该怎么做:
Please add a permissions
section to your manifest.json:
请permissions
在您的 manifest.json 中添加一个部分:
{
"name": "yourExtension",
"permissions": [
"http://fromtabdomain.com"
]
}
回答by huip
I use native ajax to solve this problem.you can do that with following steps.
我使用本机 ajax 来解决这个问题。您可以按照以下步骤进行操作。
ajax = function(options, callback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.open(options.type, options.url, options.async || true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
return callback(xhr.responseText);
}
};
return xhr.send();
};
回答by Rafay
its because same origin policyset crossDomain
to true (ise jquery version 1.5 or higher)
这是因为同源策略设置crossDomain
为 true(ise jquery 1.5 或更高版本)
$.ajax({
type: "POST", //or GET
url: serviceUrl,
data: data,
crossDomain:true,
cache:false,
async:false,
success: function(msg){
//do some thing
},
error: function(jxhr){
alert(jxhr.responseText);
//do some thing
}
});