简体   繁体   English

CakePHP - 处理ajax调用中的URL

[英]CakePHP - Handling urls in ajax calls

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? 在webroot中存在的javascript文件中进行的ajax调用中处理url的更好方法是什么?因此,不是由PHP解释的?

I'm using CakePHP and require.js and therefore would not put the javascript code directly in views. 我正在使用CakePHP和require.js,因此不会将javascript代码直接放在视图中。 The only way I found was to declare a variable in the layout that receives the value of the webroot like this: 我发现的唯一方法是在布局中声明一个接收webroot值的变量,如下所示:

<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: 然后在我的js文件中,我将url硬编码到这样的ajax调用:

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

But it does not solve the problems if there are changes in the Routes file. 但如果Routes文件中有更改,则无法解决问题。 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. 我通常在完成项目后将路由更改为更友好,如果我在js文件中引用了许多ajax调用或url,这将导致一个大问题。

I usually work this way: 我通常这样工作:

In my layout header I add the following before any other javascript is included: 在我的布局标题中,我在包含任何其他JavaScript之前添加以下内容:

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

Then at my javascript files I do this: 然后在我的javascript文件中我这样做:

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

use 采用

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

Will output; 会输出;

/Users/list

in js 在js

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

I think you're working against CakePHP's conventions if you're wanting to display your app's data in JSON format. 如果您想以JSON格式显示应用程序的数据,我认为您正在针对CakePHP的约定。 Have a look at the CakePHP cookbook entry on JSON and XML views . 查看关于JSON和XML视图CakePHP cookbook条目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM