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
How to get only the Controller name and action name from URL with jQuery
提问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.pathname
for 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 path
from the url . then use split
to get controller name and action name
这将从path
url返回。然后使用split
获取控制器名称和操作名称
var path=window.location.pathname;
var abc=path.split("/");
var controller=abc[0];
var action=abc[1] || "index";