Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery从URL仅获取控制器名称和操作名称_Javascript_Jquery_Model View Controller - Fatal编程技术网

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

Javascript 如何使用jQuery从URL仅获取控制器名称和操作名称,javascript,jquery,model-view-controller,Javascript,Jquery,Model View Controller,我在我的网站中使用.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,locati

我在我的网站中使用.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;
这将从url返回
path
。然后使用
split
获取控制器名称和操作名称

var path=window.location.pathname;
var abc=path.split("/");
var controller=abc[0];
var action=abc[1] || "index";
你可以用
window.location.pathname
为了这个

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

"/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];

取决于URL的一致性和可靠性。您可以检查URL是否以
/
结尾,如果以
/
结尾,则不要将其作为子字符串。那可能对你有用。就我个人而言,我想看看你是否可以通过razor访问控制器和动作名称,并将其直接写入javascript,这样你就不必解析它了;你只知道路。之后会发生什么完全掌握在您的手中。如果不复制JS中的所有路由逻辑,这是不可能的。相反,您可能希望服务器通过负载回显此数据,以便在客户端上使用。谢谢,这是我的最终解决方案:
var manJSCmon=location.pathname.split(“/”
var local=location.protocol+'/'+location.host+“/”+manJSCmon[1]+“/”+manJSCmon[2]