【问题标题】:How to write url for XMLHttpRequest in Cakephp 2如何在 Cakephp 2 中为 XMLHttpRequest 编写 url
【发布时间】:2020-10-06 08:52:22
【问题描述】:

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

谢谢!

【问题讨论】:

标签: cakephp cakephp-2.x


【解决方案1】:

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

我做到了:

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多