Setting baseurl in cakephp

2020-07-18 05:26发布

I am working on an application which is running in CakePHP and I am using AJAX queries from within.

In all the cases for all the ajax post i have used the url as

var ht = $.ajax({
                     type: "GET",
                     url: "http://172.20.52.99/FormBuilder/index.php/forms/viewChoices/"+attribute_id,
                     async: false
                }).responseText;
var myObject = eval('(' + ht + ')');

Is there any way in CakePHP where I can give my base URL as http://172.20.52.99/FormBuilder/index.php/ and to call the base URL in all the places I want.

标签: url cakephp
7条回答
Summer. ? 凉城
2楼-- · 2020-07-18 06:09

I assume I've the same scenario: for development, the site is available at localhost/cake, whereby in production the site is deployed in the root dir of example.com. In the header I set:

<base href="<?php echo $base_url ?>" />,

in AppContoller::beforeRender() I set:

$this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));.

This works fine for everything, except JS (so thus AJAX), as it ignores base_url.

Therefore I have a workaround (uses jQuery, but easy to substitute without):

forUrl = function(url) {
    return $('base').attr('href')+url.substr(1);
}

login = function() {
    $.post(forUrl('/ajax/profileDiv'), $('#profile-login-form').serialize(),
        function(data) {
            (...)
        });
}
查看更多
登录 后发表回答