我第一次在 CakePhp2.4.5 中使用 $.ajax - 我在 stackoverflow 上阅读了很多帖子,并对 w3schools 和 jquery 网站进行了其他研究,但不明白我应该如何解决我的问题。 我想从我的第一个 View index.ctp将数据发送到 Controller
$.ajax({
type: 'POST',
url: 'meers/client',
datatype:'json',
cache: false,
data: {myVal:'Success!'},
success: function(){alert('AjaX Success')},
error: function(){alert('AjaX Failed')}
})
.done(function(){
alert('AjaX Done!');
});
警报显示“AjaX 成功”。
在我的 Controller 中我有
公共(public)函数客户端(){
if($this->请求->isAjax()){
$this->set('ajaxTest','成功');
}}
在我的第二个 View client.ctp 中,我有。
if(isset($ajaxTest)){
echo $ajaxTest;
}别的{
echo 'ajaxTest 未设置。';
}
问题。我总是在 Client.ctp View 中收到消息“ajaxTest not Set”。 我究竟做错了什么 ?或如何做?谢谢
最佳答案
我认为您的问题出在网址中,因为“meers/client”不是路线
$.ajax({
type: 'POST',
url: "<?php echo $this->Html->url(array('controller' => 'YourController','action' => 'YourAction')); ?>",
datatype:'json',
cache: false,
data: {myVal:'Success!'},
success: function(){alert('AjaX Success')},
error: function(){alert('AjaX Failed')}
})
.done(function(){
alert('AjaX Done!');
});
或者可以探测给出路由器:
$.ajax({
type: 'POST',
url: "<?php echo Router::url(array('controller' => 'YourController', 'action' => 'YourAction'), true); ?>",
datatype:'json',
cache: false,
data: {myVal:'Success!'},
success: function(){alert('AjaX Success')},
error: function(){alert('AjaX Failed')}
})
.done(function(){
alert('AjaX Done!');
});
您可以查看其他示例:
http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/
Making jquery ajax call from view to controller in cakephp 2.x
关于javascript - 使用 $.ajax post 将数据从 cakephp View 发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26306067/