cakephp - 如何在 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);
谢谢!
解决方案
没关系,我刚刚找到了另一种解决方案。
我做了:
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。
推荐阅读
- python - 在 python 中创建两个线程,一个用于阅读,一个用于询问
- reactjs - 如何获取函数的第一个参数的类型?
- asp-classic - 我该如何解决这些 ASP 重定向错误?
- android - Flutter Huawei App Linking 从链接获取信息
- python - 将数字列表输入到函数中?
- java - 在设置上写入值时出现 IllegalArgument 异常
- vue.js - 在我的 APP (Vue3) 上使用 :Value 时无法访问 V-model
- javascript - 重新加载时动态创建的表无法正确显示
- r - bigrquery:使用 dplyr 动词在 5-95 个分位数内提取平均值、最大值、最小值和 sd 不起作用
- python - python请求获取八位字节流并发布给其他人而不下载