2016-03-22 38 views
1

我正在使用CI3作爲我的一個應用程序。 我確實創建了一些使用與應用程序不同的域的api。使用ajax無法正常工作的API調用

$.ajax({ 
     url: "http://www.example.com/restapi/index.php/api/user", 
     type: "GET", 
     data: {"user_id": user_id}, 
     username: "****", 
     password: "****", 
     success: function(response){ 

     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log(textStatus, errorThrown); 
     }, 
     xhrFields: { withCredentials: true } 
    }); 

當我把這個API使用jQuery Ajax獲得一些數據,我得到錯誤

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied 

,所以我瞭解,由於不同的子域我的應用程序和API的我不能訪問它。

有什麼辦法可以訪問不同子域的api。 我在API中使用授權。

我不想調用一些PHP文件,我使用一些PHP函數調用該API,這沒有任何意義。我想直接調用API。

讓我知道如何做到這一點,並訪問API。

+0

你嘗過的jQuery的getJSON方法顯示你的代碼 – Mihai

+3

使CORS ...... – Jai

+0

您正在運行到同源策略?您可以實現CORS或使用[jsonp](https://learn.jquery.com/ajax/working-with-jsonp/)。 http://stackoverflow.com/questions/12296910/so-jsonp-or-cors – jtrumbull

回答

0

您正在打破同源策略(https://www.w3.org/TR/cors

子域名,不同口岸,不同的協議被認爲是不同的域。

<?php 
    header("Access-Control-Allow-Credentials: true"); 
    header("Access-Control-Allow-Methods: GET, OPTIONS"); //Or post 
    header("Access-Control-Allow-Origin: http://clientdomain"); 
?> 

這裏的更多詳細信息CI:https://github.com/chriskacerguis/codeigniter-restserver/issues/345

+0

我試過這個,它不工作,仍然是相同的錯誤 – user2293790

+0

試試這個到你的服務器部分:http://stackoverflow.com/questions/30920422/how-to-handle-custom-headers-with-cors-pre-flight-request-ajax-codeigniter。如果仍然無效,請嘗試$ .support.cors = true;在前端(保重:http://stackoverflow.com/questions/7852225/is-it-safe-to-use-support-cors-true-in-jquery)。這裏的另一個相同的問題解決方案:http://stackoverflow.com/questions/27186036/i18n-ns-error-dom-bad-uri-access-to-restricted-uri-denied –