簡體   English   中英

如何使用jQuery從URL獲取Controller名稱和操作名稱

[英]How to get only the Controller name and action name from URL with 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/

有人有解決方案嗎?

您可以使用window.location.pathname

對於此問題中的網址,它會返回

"/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];
window.location.pathname;

這將從網址返回path 然后使用split獲取控制器名稱和操作名稱

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM