2015-05-29 35 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

相關問題