简体   繁体   中英

Load webpage from different domain

I am creating a sample project in MVC. Suppose I have two projects A and B. In project AI have a javascript file which takes index page of project A and put it in a div having id Widget .

In project B index page I have a reference to the javascript file of project A and a div with id Widget .

On page load I want to load Project A's index page to Project B's Widget Div .

Here is my code

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);
    }
});
};

Here is another project

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>

Above sample code display index view of Project B while I want to display index view of Project A

Without full url it will not work the way you want. To enable cross domain request you need to add 2 headers to your web.configs <system.webServer> <httpProtocol> <customHeaders> <add name="access-control-allow-headers" value="content-type"/> <add name="Access-Control-Allow-Origin" value="*"/> </customHeaders> </httpProtocol> <system.webServer> Or the other way is in your Contact controller of project B to make http request to controller of project A, then you will get HTML of controller of project A without CORS issue

The second solution is

  1. Make request to the local controller

  2. In the local controller call to the code bellow, this code makes request to some url and returns all that retrieved from the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM