//前台
<div id="showIframe"></div>
$(document).ready(function() {
var url = "@Url.Action("GetPageHtml","Catalog")";$.ajax({
url: url,
type: "POST",
dataType:"json",
data: { url: "http://www.baidu.com" },
error: function () {
alert("bbb");
},
success: function (data) {
$("#showIframe").append(data);
//$("#showIframe div").hide();
//$("#showIframe>#container").show();
//$("#showIframe>#container>#content").show();
//$("#showIframe>#container>#content>.cmsPage").show();
}
});
});
//后台
//爬虫本质,发送URL请求,返回整个页面HTML
[HttpPost]
public JsonResult GetPageHtml(string url)
{
string pageinfo;
try
{
HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);
myReq.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
myReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
HttpWebResponse myRep = (HttpWebResponse)myReq.GetResponse();
Stream myStream = myRep.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.Default);
pageinfo = sr.ReadToEnd().ToString();
}
catch
{
pageinfo = "";
}
return Json(pageinfo);
}

本文介绍了一种通过前后端分离的方式实现网页内容动态加载的方法。前端使用jQuery发起AJAX请求,向后端传递URL参数并获取HTML内容,然后将返回的数据插入到指定的DOM元素中显示。后端通过发送HTTP请求获取指定URL的内容,并将其作为JSON响应返回给前端。
306

被折叠的 条评论
为什么被折叠?



