best practice to use action url while calling ajax in cakePHP

后端 未结 5 1375
失恋的感觉
失恋的感觉 2020-12-28 11:00

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

相关标签:
5条回答
  • 2020-12-28 11:32

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

    0 讨论(0)
  • 2020-12-28 11:38

    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'});
    
    0 讨论(0)
  • 2020-12-28 11:44

    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')); ?>"})
    
    0 讨论(0)
  • 2020-12-28 11:45

    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.

    0 讨论(0)
  • 2020-12-28 11:53

    @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')); ?>'
    
    0 讨论(0)
提交回复
热议问题