如何在 Cakephp 2 中为 XMLHttpRequest 写 url

How to write url for XMLHttpRequest in Cakephp 2

如何为我的 XMLHttpRequest 编写 url 以便我可以将数据发送到我的控制器。

我现在拥有的是:

var data = `post=${post}`;
var xhr = new XMLHttpRequest;
xhr.open("POST" , "<?= Router::url(array('controller'=>'posts','action'=>'add')) ?>", true);
xhr.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
xhr.send(data);

我知道我可以:

xhr.open("POST" , "/cakephp/posts/add/", true);

但我想要的是指定确切的控制器和操作,这样即使我更改网站名称也不会更改代码,例如:

xhr.open("POST" , "/mywebsitename/posts/add/", true);

谢谢!

没关系,我只是找到了替代解决方案。

我做到了:

var hostname = window.location.origin;
var data = `post=${post}`;
var xhr = new XMLHttpRequest;
xhr.open("POST" , hostname + "/posts/add", true);
xhr.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
xhr.send(data);

这样它会自动获取我网站的基础URL。