![](/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.