duangu1033 2013-09-26 14:20
浏览 46

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.

  • 写回答

3条回答 默认 最新

  • douchuo9476 2013-09-26 14:26
    关注

    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");
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!