简体   繁体   English

带参数的CakePHP控制器函数不显示javascript

[英]CakePHP controller function with parameters doesn't show javascript

When I'm using controller function with parameters the rendered view just seems to forget every included .js files. 当我使用带参数的控制器功能时,渲染视图似乎忘记了每个包含的.js文件。

public function view($id = null) {
    if(!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    $post = $this->Post->findById($id);

    if(!$post) {
        throw new NotFoundException(__('Invalid post'));
    }
    $this->set('post', $post);
}

If I take parameters away and put variable '$id = 1' on function the view with postID 1 renders okay in 'posts/view'. 如果我取走参数并将变量'$ id = 1'放在函数上,则使用postID 1的视图在'posts / view'中呈现正常。

I included javascript files to default.ctp in traditional way: 我以传统方式将javascript文件包含到default.ctp:

echo "script type='text/javascript' SRC='../js/jquery-1.9.1.min.js'></script>";);

(it includes '<' but this text editor won't me type it for safety reasons I guess) (它包括'<'但是这个文本编辑器我不会因为安全原因而输入它我猜)

I don't have knowledge about 'js helpers' of cakePHP. 我不了解cakePHP的'js helpers'。 Can't I use javascript in traditional way? 我不能用传统方式使用javascript吗?

Site renders okay in every other view (eg posts/add) and .js files are included in source code of 'posts/view/1' 网站在每个其他视图中呈现正常(例如帖子/添加)和.js文件包含在'posts / view / 1'的源代码中

The problem 问题

You're using relative paths to the javascript; 你正在使用javascript的相对路径;

<script src='../js/jquery-1.9.1.min.js'></script>

In this url, ../ means '1 directory up from the current location`, so when you're currently visiting this URL; 在这个网址中, ../表示“从当前位置向上的1个目录”,所以当您正在访问此网址时;

http://mysite.com/home/

Then your browser will correctly try to load the script from; 然后您的浏览器将正确尝试加载脚本;

http://mysite.com/js/jquery-1.9.1.min.js

However, if you're visiting this url; 但是,如果你正在访问这个网址;

http://mysite.com/home/and/some/more/

Then the browser will look for the JavaScript here: 然后浏览器会在这里查找JavaScript:

http://mysite.com/home/and/some/js/jquery-1.9.1.min.js

How to fix the problem 如何解决问题

  1. Use absolute paths for all 'assets' (CSS, JavaScript, Images); 对所有'资产'使用绝对路径(CSS,JavaScript,图像); src='/js/jquery-1.9.1.min.js'
  2. Output the script-tags using CakePHP Helpers (after all, that's what they are meant for: to simplify your work :), eg echo $this->Html->script('jquery-1.9.1.min'); 使用CakePHP Helpers输出脚本标签(毕竟,这就是它们的意思: 简化你的工作:),例如echo $this->Html->script('jquery-1.9.1.min');

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

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