简体   繁体   English

Javascript调用相对路径,而不是从Web根目录

[英]Javascript calls relative paths and not from web root

When I'm calling files within javascript from example Ajax or other functions, the javascript tries to call it relative to the current address, and not from the baseURL or root. 当我从示例Ajax或其他函数调用javascript中的文件时,javascript会尝试相对于当前地址而不是从baseURL或root调用它。

Example if I'm on domain.com/my-page/ and I try to call a php file using 例如,如果我在domain.com/my-page/上,并且尝试使用以下方式调用php文件

$.post('ajax/class.designer.php', { action: 'getcard', cardID: id },
        function(data) {
            loadCard(data)
        }, "json");

it tries to call domain.com/my-page/ajax/class.designer.php, when I actually want it to call domain.com/ajax/class.designer.php . 当我实际希望它调用domain.com/ajax/class.designer.php时,它会尝试调用domain.com/my-page/ajax/class.designer.php。

Same with plugins such as CKEditor tries to call it's .css files relative to the current address. 与诸如CKEditor之类的插件一样,它尝试调用相对于当前地址的.css文件。

The application is using mod_rewrite and friendly url's. 该应用程序使用mod_rewrite和友好的url。 Everything is redirected to index.php which is located in / and from index.php I then call the functions to display the page. 一切都重定向到/中的index.php,并从index.php重定向到该函数,然后调用该函数以显示该页面。

I've set RewriteBase / and I've also set baseurl in my HTML head to the root path. 我已经设置了RewriteBase /,并且还将我的HTML头中的baseurl设置为根路径。

Note: Everything worked fine when I was running it on my localhost. 注意:在本地主机上运行时,一切正常。 The issue started when I moved it to my live server. 当我将其移至实时服务器时,问题就开始了。

Put a slash in front of ajax ie /ajax . 在ajax前面加一个斜线,即/ajax When you leave the slash off you're going to get the relative path, ie the path relative to where you are. 当不使用斜线时,您将获得相对路径,即相对于您所在位置的路径。 To get an absolute path always start with a / . 要获得绝对路径,请始终以/开头。

An alternative to the answer above is that you could add a base tag in the head. 上述答案的替代方法是,您可以在头部添加一个基本标签。 This will tell the browser where to start all relative paths. 这将告诉浏览器从哪里开始所有相对路径。 With your particular issue, you would add: 对于您的特定问题,您将添加:

<base href="http://domain.com">

This would cause any relative URL's you add to start from root. 这将导致您添加的所有相对URL都从root开始。

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

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