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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28946447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:48:47  来源:igfitidea点击:

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

javascriptjquerymodel-view-controller

提问by user4612487

I am using .net MVC in my website and I need to get the URL in javascript, but only the controller and action name, for instance if i have:

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

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

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

I need:

我需要:

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

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

I have found some solutions such as:

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

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

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

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

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

However if my URL does not have any parameters I the action name is cut off like so:

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

http://stackoverflow.com/questions/

http://stackoverflow.com/questions/

Does anyone have a solution for this?

有没有人对此有解决方案?

回答by jimmy jansen

You can use window.location.pathnamefor this.

您可以window.location.pathname为此使用 。

For the url in this question it returns

对于这个问题中的网址,它返回

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

To read it properly you can use: window.location.pathname.split("/")
Read the value with:

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

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

回答by balajisoundar

window.location.pathname;

this will return pathfrom the url . then use splitto get controller name and action name

这将从pathurl返回。然后使用split获取控制器名称和操作名称

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