最近在做个后台系统,之前都是用iframe来实现加载内容,左侧菜单不刷新。但一直不喜欢这种方法,有许多弊端。今天自己在网上查找了一番后找到了比较好的替代方案:
一、利用html的锚点标记来实现无刷新页面加载:
Index.cshtml:
<!DOCTYPE html><html><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/><metacharset="utf-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>局部刷新demo</title>@Scripts.Render("~/bundles/jquery")</head><body><ahref="#/~Demo1">Demo1</a><
br><ahref="#/~Demo2">Demo2</a><
br><ahref="#/~Demo3">Demo3</a><
br><divid="content"><h1>Index</h1></div><scripttype="text/javascript">$('a').each(function() {this.onclick=function() {
$.get(this.href.split('#/~')[1],function(data) {
$('#content').html(data);
});
};
});</script></body></html>
Demo2.cshtml:
<h2>Demo2</h2><h2>Demo2</h2>
其它,demo1,demo3就不贴上来了。
DemoController:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;namespaceMvcDemo.Controllers
{publicclassDemoController : Controller
{//GET: DemopublicActionResult Index()
{returnView();
}publicActionResult Demo1()
{returnView();
}publicActionResult Demo2()
{returnView();
}publicActionResult Demo3()
{returnView();
}
}
}
然后运行就可以看到效果了。弊端就是地址栏路径会显示点击加载页面的路径。
二、利用jQuery.load()方法
方法说明:load(url,[data],[callback]);
load方法与html方法类似,不过load是远程加载html代码,而且被加载的html里包含的js可以正常运行。废话不多说,上代码:
Index.cshtml
<!DOCTYPE html><html><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/><metacharset="utf-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>局部刷新demo</title>@Scripts.Render("~/bundles/jquery")</head><body><ahref="#"data-link="Demo1">Demo1</a><
br><ahref="#"data-link="Demo2">Demo2</a><
br><ahref="#"data-link="Demo3">Demo3</a><
br><divid="content"><h1>Index</h1></div><scripttype="text/Javascript">$('a').each(function() {this.onclick=function() {
$('#content').load($(this).data("link"));
};
});</script></body></html>
注意是显示内容的容器调用load。
第一次写博客,语言组织能力不行,如有不对的,欢迎提出!