Get base_url using Jquery in Laravel

2019-01-25 22:23发布

I am using laravel 5.0. I want to get base url of laravel page using jquery. I have tried the following function.

function getBaseURL () {
   return location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
}

But this gives only http://localhost. I need my full base url in jquery. What to do?

3条回答
家丑人穷心不美
2楼-- · 2019-01-25 22:41

You can also use this:

<script type="text/javascript">
      var base_url = '{!! url() !!}';
</script>

You can call it any where in js files like "base_url"

It return upto your public path without slash at end

Ex: www.example.com

If you need to add slash at end you can use this..

<script type="text/javascript">
      var base_url = '{!! url().'/' !!}';
</script>

It return upto your public path with slash at end

Ex: www.example.com/

查看更多
爷、活的狠高调
3楼-- · 2019-01-25 22:48

Do you mean you want the base url of your laravel app available anywhere your javascript?

You can include this in your template.blade.php:

<script type="text/javascript">
var APP_URL = {!! json_encode(url('/')) !!}
</script>

And than access that var anywhere in your javascript:

console.log(APP_URL);
查看更多
来,给爷笑一个
4楼-- · 2019-01-25 22:48

The solution is easy , All you need to just use below code :-

var appBaseUrl = {''};

This variable will return something like http://yourexampledomain.com

Furthermore if you want to add your controllers and action to this url i.e. for Ajax call , then that will be simple too :-

var finalUrl = appBaseUrl+'/controller/action';

Result is :- http://yourexampledomain.com/controller/action

Now use finalUrl in your calling route for ajax calls.

查看更多
登录 后发表回答