【发布时间】:2018-05-20 10:59:31
【问题描述】:
我在使用 CakePHP 和 Javascript 方面还很新,我阅读了很多关于 cake 中请求处理的文章,但我仍然感到困惑,我正在尝试做的是将 ajax 请求从我的 Javascript 代码发送到 cakePHP 和获取一些 json 格式的数据,我尝试了很多方法来做到这一点,但我一直只得到页面的 html,而不是我想要获取的数据,我默认生成了应用程序控制器类,作为 Javascript 请求中的 url 我使用“http://localhost/pages/main”,这是我有输入控件的视图页面的 url,我想知道我应该在控制器类中的哪个位置放置负责处理请求的代码,以及如何实现发送 json 响应,提前谢谢
php代码AppController类
public function beforeRender(Event $event)
{
// Note: These defaults are just to get started quickly with development
// and should not be used in production. You should instead set "_serialize"
// in each action as required.
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
if ($this->request->is('ajax')) {
$data = ['data1', 'data2'];
$this->set(compact('data'));
$this->set('_serialize', ['data']);
}
}
**javascript:**
var xhr = new XMLHttpRequest();
var url = 'localhost/pages/main.json';
var data = {
unit: 'someUnit',
name: this.name
};
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.response);
}
};
xhr.open('POST', url);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(data);
【问题讨论】:
-
你能给我们看看你的 PHP 和 JS 代码吗?
标签: javascript php jquery ajax cakephp