![](/img/trans.png)
[英]How to load a certain div of an external webpage on another webpage that is on a different domain
[英]Load webpage from different domain
我正在MVC中創建一個示例項目。 假設我有兩個項目A和B。在項目AI中,有一個javascript文件,該文件將project A
索引頁放入具有id Widget
的div中。
在project B
索引頁中,我引用了項目A的javascript文件和ID為Widget
的div。
在頁面加載時,我想將Project A's index page
加載到Project B's Widget Div
。
這是我的代碼
Project A
Index.cshtml (Index view)
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="data">Thi is index page.</div>
Widget.js (JavaScript file)
$(document).ready(function (e) {
$('#widget').load('/Home/Contact', function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
});
};
這是另一個項目
Project B
Index view which call the project A's index view
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://localhost:2455/Scripts/Widget.js"></script>
<div id="widget"></div>
<div>Project B Index</div>
上面的示例代碼顯示項目B的索引視圖,而我想顯示項目A的索引視圖
沒有完整的URL,它將無法按您想要的方式工作。 要啟用跨域請求,您需要向web.configs中添加2個標頭<system.webServer> <httpProtocol> <customHeaders> <add name="access-control-allow-headers" value="content-type"/> <add name="Access-Control-Allow-Origin" value="*"/> </customHeaders> </httpProtocol> <system.webServer>
或另一種方式是在項目B的Contact控制器中向控制器發出http請求項目A的代碼,那么您將獲得項目A的控制器的HTML,而沒有CORS問題
第二個解決方案是
向本地控制器發出請求
在下面的代碼的本地控制器調用中,此代碼向某個URL發出請求,並返回從URL中檢索到的所有內容。
var html = ""; StreamReader reader = null; WebResponse response = null; try { var request = WebRequest.Create("url of project A controller"); response = request.GetResponse(); var dataStream = response.GetResponseStream(); reader = new StreamReader(dataStream); //here you will get HTML of controller from project A html = reader.ReadToEnd(); } finally { if (reader != null) { reader.Close(); } if (response != null) { response.Close(); } } ViewBag.HTML = html;//And then you can use the HTML inside of current controller, simply put @ViewBag.HTML inside of the div.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.