php - 无法从 Codeigniter 中的 JQuery Ajax 请求中检索 Post 数据

标签 php jquery ajax codeigniter

我正在使用 AJAX 创建过滤机制,在我的代码中,我从过滤字段中获取数据并通过 AJAX 请求将它们发送到 Controller ,当我收到数据时我会相应地更新表。

这是我的 Ajax 脚本:

var suppliername = "Apple";
jQuery.ajax({            
    type: "POST",           
    url: "<?php echo base_url(); ?>index.php/Welcome/get",            
    dataType: "json",
    data: {
        supplier_name: suppliername,
    },
    success: function(html){
        console.log("yay");
        hot.loadData(html);         
    }        
}); 

这是我的 Controller :

public function get(){
        $where="";

        $field="supplier_name";
        $value=$this->input->post($field);
        if($value!= null){
            $supplier_name = $value;
            $where = $where.$field.'="'.$value.'"';
            $where = $where." AND ";
        }
        else{
            $where = $where.$field.'='.$field;
            $where = $where." AND ";
        }

        $field="category";
        $value=$this->input->post($field);
        if($value!= null){
            $supplier_name = $value;
            $where = $where.$field.'="'.$value.'"';
            //$where = $where." AND ";
        }
        else{
            $where = $where.$field.'='.$field;
            //$where = $where." AND ";
        }

        echo json_encode($this->inventory_m->get(null,$where));
        die();
    }

当我手动编辑 Controller 中的值时,过滤器工作正常,但是当我使用 $this->input->post($field) 时它什么都不做,我尝试打印 get 和 post 数组,但两者都是空的.

最佳答案

我不能发表评论,所以我将其作为答案发布。

这是我对问题的解决方案和解释。这与 CodeIgniter 无法获取 JSON 有关。 jQuery 做了一些幕后技巧并将您的数据转换为 form-data-x,这就是它起作用的原因。

解决方案是使用 $this->input->raw_input_stream 获取您的 JSON 并使用 php 对其进行解码>json_decode。检查下面的完整答案和代码:

Retrieve JSON POST data in CodeIgniter

关于php - 无法从 Codeigniter 中的 JQuery Ajax 请求中检索 Post 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30784355/

相关文章:

javascript - react : how to get input value from one component to make the ajax call in another component?

php - 在 Php 数组中搜索字符串并提取相邻文本

javascript - ajax点击功能可以在提交表单时起作用吗?

javascript - 开发模式下 Rails 3.2 的请求处理顺序

javascript - jquery 关闭 ('scroll' ) 不工作

javascript - ThreeJS 新网格 vs 克隆

javascript - 如何通过 jquery 将点击更改为鼠标悬停或悬停?

PHP - 如何在没有 MySQL 的情况下订购图像

php - 在 php 中调整大小后显示图像出错

php - 使用 OROPlatform 时如何测试我自己的代码?