如何使用jQuery从URL获取Controller名称和操作名称

use*_*487 4 javascript model-view-controller jquery

我在我的网站上使用.net MVC,我需要在javascript中获取URL,但只需要控制器和操作名称,例如,如果我有:

http://stackoverflow.com/questions/9513736/current-url-without-parameters-hash-https

我需要:

http://stackoverflow.com/questions/9513736/

我找到了一些解决方案,例如:

urlBase = location.href.substring(0, location.href.lastIndexOf("/")+1)

->http://stackoverflow.com/questions/9513736/

但是,如果我的URL没有任何参数,则操作名称将被截断,如下所示:

http://stackoverflow.com/questions/

有人有解决方案吗?

小智 21

你可以用 window.location.pathname 它.

对于此问题中的网址,它会返回

"/questions/28946447/how-to-get-only-the-controller-name-and-action-name-from-url-with-jquery"
Run Code Online (Sandbox Code Playgroud)

要正确阅读,您可以使用:window.location.pathname.split("/")
读取值:

var url = window.location.pathname.split("/");
var questions = url[1];
Run Code Online (Sandbox Code Playgroud)