CakePHP - 处理ajax调用中的URL

What is the better way to deal with urls in ajax calls made in javascript files present in the webroot and because of that, are not interpreted by PHP?

I'm using CakePHP and require.js and therefore would not put the javascript code directly in views. The only way I found was to declare a variable in the layout that receives the value of the webroot like this:

<script>var webroot = "<?php echo this->Html->url('/') ?>" </script>

And then in my js files I hardcoded the urls to the ajax calls like this:

$.getJSON(webroot + 'users/list', function(){ ... } );

But it does not solve the problems if there are changes in the Routes file. I generally change the routes to be more friendly after I finished the project and this would cause a big problem if I have many ajax calls or urls been referenced in js files.

I usually work this way:

In my layout header I add the following before any other javascript is included:

<script type="text/javascript">var baseUrl = '<?php echo $this->base; ?>';</script>

Then at my javascript files I do this:

$.post("http://"+ document.domain + baseUrl +"/controller/action.json");

I think you’re working against CakePHP’s conventions if you’re wanting to display your app’s data in JSON format. Have a look at the CakePHP cookbook entry on JSON and XML views.

use

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

Will output;

/Users/list

in js

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