Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

root url javascript

I'm working on an .Net ASP MVC razor application

The root url on the server being "myWebSite.com/myApp/"

I need to find dynamically this url to have the right url to make some Ajax call to action like this

    $.ajax(
    {
        type: "POST",
        url: root + "/Controller/Action",
        data: ...
    }

I read a few things here and there but what I found doesn't work

"document.location.hostname" -> "myWebSite.com"
"location.host"              -> "myWebSite.com"
"window.location.pathname"   -> "/myApp/"

Last one sounded promissing but if I navigate in the website :

 for an url :  "myWebSite.com/myApp/Controller/Action?1" 
 "window.location.pathname"   -> "/myApp/Controller/Action"
like image 258
Rachid Avatar asked Jul 31 '11 19:07

Rachid


People also ask

How to get base URL in javascript?

In Chrome Dev Tools, you can simply enter window. location in your console and it will return all of the available properties. Save this answer.

How do I find the hostname of a URL?

The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').

What is host in Javascript?

host property returns the host (IP adress or domain) and port of a URL. The location. host property can also be set, to navigate to the same URL with a new host and port.


2 Answers

In asp.net mvc, using razor view engine, I got this in my layout:

<script type="text/javascript">
 var baseUrl = "@Url.Content("~")";
</script>

That way we can define application base url as javascript object that is accessible from everywhere.

like image 82
Arnis Lapsa Avatar answered Oct 04 '22 23:10

Arnis Lapsa


You don't need to find this. Use realtive path:

    $.ajax(
    {
        type: "POST",
        url: "Controller/Action",
        data: ...
    }

This will go in as <root>/Controller/Action

like image 23
Mrchief Avatar answered Oct 04 '22 23:10

Mrchief