【问题标题】:Ajax function call: parameter passing to controller function in codeigniterAjax 函数调用:参数传递给 codeigniter 中的控制器函数
【发布时间】:2018-07-20 15:13:36
【问题描述】:

我正在开发 codeigniter。我在视图页面中调用 ajax 函数。阿贾克斯 函数正在调用控制器方法。 Ajax 函数包含 3 我想传递给控制器​​方法但由于某种原因我的参数 我无法访问来自 ajax 函数的参数。

下面是我的视图代码:

<script>  
$('#drp').change(function(e){  
      var costcenter = $('#costcenter_id :selected').val(); 
      var location1 = $('#location_id :selected').val(); 
      var department = $('#department_id :selected').val(); 
      $.ajax({
         cashe: false,
         type: 'POST',
         data:  {'costcenterid':costcenter,'locationid':location1,
                 'departmentid':department},
         url: 'http://local.desk.in/mycontroller/contollerfunction',
success: function(data)
            {
               alert("success");
            }
      });
    });
 </script>
// controller method
public function controllerfunction($costcenterid,$locationid,$departmentid)
    {
    echo "costcenter= ". $costcenterid; 
    echo "location= ". $locationid; 
    echo "department= ". $departmentid;
    }

收到错误信息:

消息:assetcontroller::controllerfunction() 缺少参数 1, 消息:assetcontroller::controllerfunction() 缺少参数 2, 消息:assetcontroller::controllerfunction() 缺少参数 3

为什么不能将 ajax 参数值发送到控制器方法?谢谢在 前进

【问题讨论】:

    标签: php codeigniter parameters codeigniter-3


    【解决方案1】:

    希望对您有所帮助:

    您在 ajax 中将数据作为 post 传递,因此您必须使用 $_POST 或使用 CI 输入类(如 $this-&gt;input-&gt;post())访问您的数据,对于 url 路径使用 site_url()

    您的ajax 代码应该是这样的:

    $('#drp').change(function(e){  
        var costcenter = $('#costcenter_id :selected').val(); 
        var location1 = $('#location_id :selected').val(); 
        var department = $('#department_id :selected').val(); 
        $.ajax({
            cache: false,
            type: 'POST',
            data:  {'costcenterid':costcenter,'locationid':location1,
             'departmentid':department},
            url: "<?=site_url('mycontroller/contollerfunction');?>",
            success: function(data)
            {
               alert("success");
            }
        });
    });
    

    你的控制器 controllerfunction 方法应该是这样的:

    public function controllerfunction()
    {
        $costcenterid = $this->input->post('costcenterid');
        $locationid = $this->input->post('locationid');
        $departmentid = $this->input->post('departmentid');
        $posts = array('costcenterid' => $costcenterid,
                       'locationid' => $locationid,
                       'departmentid' => $departmentid);
        print_r($posts);die;
    }
    

    注意:查看浏览器的网络选项卡以查看输出:

    【讨论】:

    • 非常感谢。我按照您的建议尝试了现在我可以访问控制器方法中的所有参数值。非常感谢您的帮助。
    • 您能否建议调试 PHP 程序的最佳方法是什么?是否有可用于编写和调试 PHP 程序的编辑器?提前致谢。
    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2019-06-27
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多