使用 $.ajax post 将数据从 cakephp 视图发送到控制器

2023-12-28

我第一次在 CakePhp2.4.5 中使用 $.ajax - 我阅读了很多 stackoverflow 上的帖子,并对 w3schools 和 jquery 网站进行了其他研究,但无法理解我应该如何解决我的问题。 我想从第一个视图 index.ctp 将数据发送到控制器

 $.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 成功”。

在我的控制器中我有

public function client(){ if($this->request->isAjax()){ $this->set('ajaxTest','Success'); }}

在我的第二个视图 client.ctp 中我有。

if(isset($ajaxTest)){ echo $ajaxTest; }else{ echo 'ajaxTest not Set.'; }

问题。我总是在 Client.ctp 视图中收到消息“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/ http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/

在 cakephp 2.x 中从视图到控制器进行 jquery ajax 调用 https://stackoverflow.com/questions/18440905/making-jquery-ajax-call-from-view-to-controller-in-cakephp-2-x

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 $.ajax post 将数据从 cakephp 视图发送到控制器 的相关文章

随机推荐