best practice to use action url while calling ajax

2019-02-02 18:18发布

问题:

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')); ?>"})