首页 > 解决方案 > 如何在 Cakephp 2 中为 XMLHttpRequest 编写 url

问题描述

如何为我的 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);

谢谢!

标签: cakephpcakephp-2.x

解决方案


没关系,我刚刚找到了另一种解决方案。

我做了:

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。


推荐阅读