2015-05-29 33 views
0

在我的php代码中,我使用了以下Ajax请求。在Chrome浏览器控制台中显示以下错误的Ajax请求XAMPP中请求的资源上没有'Access-Control-Allow-Origin'标头

XMLHttpRequest无法加载http://example.com/posts。请求的资源上没有“Access-Control-Allow-Origin”标题。因此不允许访问原产地'http://localhost'。 (指数):

我的代码:

<script> 
    $(document).ready(function() { 
     var title = 'Tes ajax'; 
     var raw = 'very good'; 

     //Validate fields if required using jQuery 

     var postForm = { //Fetch form data 
      'api_key'  : 'bf_apikey', 
      'api_username': 'username', 
      'title'  : title, 
      'raw'   : raw, 
      'category' :'categoryname'//Store name fields value 
     }; 

     $.ajax({ //Process the form using $.ajax() 
      type  : 'POST', //Method type 
      url  : 'http://example.com/posts', //Your form processing file URL 
      data  : postForm,   //Forms name 
      dataType : 'application/json', 
      success: updatesuccess, 
      error: updatefailure 
      // return response; // <- tried that one as well 
     }); 
     function updatesuccess(result) 
     { 
      alert(result+"Successs") 
     } 

     function updatefailure() 
     { 
      alert("failure") 
     }   

    }); 
</script> 

请提出更好的选择来解决这个错误。

+0

http://stackoverflow.com/questions/ 10143093 /原产地不允许通过访问控制允许来源 – Izion

回答

0

CORS问题队友。三种可能的解决方案:

1)JSONP;

2)在同一个域上创建代理,将您的请求发送给代理并使用代理来调用服务;

3)如果您有“example.com”(你正在做的Ajax调用其中的源),然后添加下列头接入:header('Access-Control-Allow-Origin: *');

+0

我试着用你的第一个解决方案。那不是工作我仍然得到相同的错误。并且我尝试了第三个解决方案。但是我有一个怀疑需要添加标题的位置('Access-Control-Allow-Origin:*'); – Team

相关问题