best practice to use action url while calling ajax in cakePHP

拈花ヽ惹草 提交于 2019-12-18 11:13:46

问题


I am using ajax with jQuery in my cakePHP application.
and my javascript function is placed inside a javascript file.

now in my local system the files are kept in "/sample" directory so the the path while i call the function will be

in ajax.js

$.post({url : "/sample/controller/action"})

but after hosting it the url will become

$.post({url : "/mydomain.com/controller/action"})

in cakePHP we $html->url to generate urls
but since this code is in js file i can't use that function

i don't want to change the all ajax action urls manually before hosting


回答1:


What to do is in your master template for your cake app create a global javascript variable that can be used throughout your application. Make sure it exists befor you do any JS includes too.

<head>
    ...
    <script type="text/javascript">var myBaseUrl = '<?php echo $html->url; ?>';</script>
    ...
    <script type="text/javascript" src="mycustomJSfile.js">
    ...
</head>

Now you can do things like this from any view file you have in your MVC framework app.

$.post({url: myBaseUrl + 'controller/action'});



回答2:


I'm updating Paul Dragoonis's answer to reflect the latest CakePHP version (2.2).

In your layout file, set the JavaScript variable with CakePHP's JSHelper: <?php echo $this->Js->set('url', $this->request->base); ?>, where $this->request is an instance of CakeRequest and gives information on the current request.

After the line above, write the buffer with <?php echo $this->Js->writeBuffer(); ?>.

Then, you can access this variable in JavaScript with app.url.




回答3:


@irtiza your answer is appreciated but for cakephp latest version 3.x this will work otherwise you will get routing error.

ulr:'<?php echo \Cake\Routing\Router::url(array('controller' => 
'controllername', 'action' => 'actionname')); ?>'



回答4:


in reply to Paul Dragoonis you can use $this->webroot if you use subfolders.




回答5:


use

echo Router::url(array('controller' => 'Users', 'action' => 'all'));

Will output;

/Users/all

in js

$.post({url : "<?php echo Router::url(array('controller' => 'Users', 'action' => 'all')); ?>"})


来源:https://stackoverflow.com/questions/3352350/best-practice-to-use-action-url-while-calling-ajax-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!