2012-04-24 25 views
1

我有以下的情況。GET子域的HTML頁面的jQuery

從位於應用程序https://subdomain.mydomain.com我試圖讓位於https://mydomain.com/page.aspx

我一個頁面的HTML 「M與jQuery的$就方法這樣做。

$.ajax({ 
     url: url, 
     type: 'GET', 
     contentType: 'application/x-www-form-urlencoded', 
     success: function (data, status, xhr) { 
      console.info("success"); 
     }, 
     error: function (xhr, status, error) { 
      console.error(error); 
     } 
    }); 

ASPX頁面實際上是調用和執行。我看到響應狀態是200 OK並且它具有預期的大小(80KB),但響應內容(80KB)是空的。 jQuery的錯誤也不是那麼有用:

readyState: 0, 
    responseText: "" 
    status: 0, 
    statusText: "error" 

我想這是涉及同源策略的東西。我看到人們用YQL解決這類問題(但我不想使用額外的庫)和JSONP(但我使用純HTML)。

在絕望的時刻我也嘗試的技巧,比如

document.domain = 'mydomain.com'; 
    jQuery.support.cors = true; 

沒有成功。任何提示?


的問題是由於必須對所謂的應用程序啓用了Access-Control-Allow-Origin。在我的情況下,它是IIS7託管中的一個asp.net應用程序。我不得不在web.config中添加這些行:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<system.webServer> 
    <httpProtocol> 
    <customHeaders> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
    </customHeaders> 
    </httpProtocol> 
</system.webServer> 
</configuration> 

以下網站報道,許多配置enable CORS在許多服務器類型

回答

3

爲了使用IE的或FF的跨域請求您需要調整您的服務器端發送Access-Control-Allow-Origin頭與響應。如果你想使用document.domain,它不僅在請求方,而且在響應中也必須設置。因此,您可以使用iframe發送此類請求,或者使用SCRIPT或JSONP,因爲它們沒有跨源限制。

+0

工作正常!我只需要添加到正確的服務器配置。此鏈接幫助了我很多 http://enable-cors.org/ 感謝您的幫助! – abx78 2012-04-24 20:12:58

1

使用JSONP獲取數據

function myFunc() { 
    console.info("success"); 
} 

$.ajax({ 
    url: url, 
    'dataType': "jsonp", 
    'jsonp': "callback", 
    'jsonpCallback': "myFunc" 
}); 

問題是你試圖從另一個域發出XHR請求,這是不允許的。你告訴jQuery允許CORS,但是JSONP是更好的方法。您需要設置服務器端代碼,以便在加載URL時調用封裝在函數中的JSON數據返回HTML。

+0

,當我不得不面對現有的JSON服務,我會考慮這個選項。感謝您的幫助! – abx78 2012-04-24 20:21:42

+0

這是非常可以理解的。我最近有一個類似問題的項目。我設置了服務器端代碼來偵聽'?callback = xxx'查詢字符串,並將所有HTML都返回給JSON變量而不是純HTML響應。我想我應該在我的答案中提到這一點。 – honyovk 2012-04-24 20:36:43

0

如簡單的JavaScript就足夠了

alert(document.domain); 

console.log("Output;"); 
console.log(location.hostname); 
console.log(document.domain); 
alert(window.location.hostname) 

console.log("document.URL : "+document.URL); 
console.log("document.location.href : "+document.location.href); 
console.log("document.location.origin : "+document.location.origin); 
console.log("document.location.hostname : "+document.location.hostname); 
console.log("document.location.host : "+document.location.host); 
console.log("document.location.pathname : "+document.location.pathname);