进行 Ajax 调用时基数 URL 发生变化

Base URL is changing when making Ajax call

我有一个 CakePHP 3.x 应用程序,其中一些 API 从 AJAX 调用。

在 AJAX 上,我这样调用 url:

url: 'user/id/' + id,
method: 'get',
dataType: 'json'
// ...

等等

我的url是http://localhost:8090/users

所以 url 上的 ajax 就像 http://localhost:8090/currentpage/users/id/

但由于某些原因,有时 url 会更改为 http://localhost:8090/users/id/

我应该改变什么? 发生了什么事?

发生这种情况是因为您在 URL 中的操作(参数)。

下面是一些示例,以便您更好地理解它。

假设我们项目的每个页面都有一个 link。 单击此处添加新用户

此 link 将根据您当前的 URL

创建不同的 URL
Current URL                                       URL generate by LINK
localhost/products  (here index is the method)    localhost/users/add
localhost/products/add                            localhost/products/users/add
localhost/products/edit/1                         localhost/products/edit/users/add

要解决此问题,请在开头使用“/”并提供来自您的 webroot 的路径

我认为其他答案是正确的。

关于如何解决它,我通常做的是将 CakePHP 返回的 webroot 保存在 javascript 变量中。通过在模板文件的 header 中执行此操作,它将随处可用:

<!-- src/Templates/Layout/default.ctp -->
<head>
    <script>
         var webroot = <?= $this->request->webroot ?>
    </script>
</head>

当您想要创建一个 Ajax 调用时,使用从 Javascript:

生成的 URL
url: webroot + "user/id" + id //...

现在,无论您的应用程序放置在网络服务器上的哪个位置,调用都将按预期进行。