如何使用 jQuery 从 URL 中仅获取控制器名称和操作名称

How to get only the Controller name and action name from URL with jQuery

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

我需要:

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

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

->

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

http://whosebug.com/questions/

有人对此有解决方案吗?

window.location.pathname;

这将从 url return path 。然后使用 split 获取控制器名称和操作名称

var path=window.location.pathname;
var abc=path.split("/");
var controller=abc[0];
var action=abc[1] || "index";

你可以使用 window.location.pathname 为了这。

对于本题中的url它returns

"/questions/28946447/how-to-get-only-the-controller-name-and-action-name-from-url-with-jquery"

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

var url = window.location.pathname.split("/");
var questions = url[1];