2011-07-23 156 views
9

我用jquery.ajax函数从谷歌浏览器扩展数据发布到我的web服务,如下代码使用jQuery.ajax:在谷歌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(); 
       } 
      } 
     }); 

,但我得到一个错误:

XMLHttpRequest cannot load http://todomain.com/Service.asp. Origin http://fromtabdomain.com is not allowed by Access-Control-Allow-Origin. 

我该如何解决它?

回答

0

其因为same origin policy设置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 
      } 
     }); 
+0

我按照你的说法尝试,但它不能解决我的问题。 –

+0

你得到同样的错误?你是否尝试过'type:'GET''? – Rafay

+0

感谢您的回答,但我想将数据发布到我的服务中。 –

0

我用原生Ajax来解决这个problem.you可以做到这一点下面的步骤。

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

你需要一个许可添加到您manifest.js文件

"permissions": [ 
    "http://www.yourwebsite.com/" 
    ], 
+2

我收到一个错误 - URL未知或格式错误 – user6031759

+0

请确保包含斜线,否则将无法使用。 – joe