无法访问控制器中的提取帖子数据:Codeigniter [英] Can't access fetch post data in controller: Codeigniter

查看:74
本文介绍了无法访问控制器中的提取帖子数据:Codeigniter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的codeigniter项目中使用fetch发出发布请求.请求看起来像这样

I'm making a post request using fetch in my codeigniter project. The request looks like this

fetch('myurl/mycontroller', {
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
         testdata: 123,
    })
 }).then((res) => {
    console.log(res);
 }).catch(console.log);

我的控制器如下所示

class MyController extends CI_Controller
{
    public function mycontroller()
    {
        $data = $this->input->post('testdata');
        return $data . " is the passed data.";
    }
}

但是数据没有传递到我的控制器.我回显了 $ _ POST ,它给了我一个空数组.知道我在做什么错吗?我正在使用Codeigniter 2(我知道它已经很旧了)

But the data isn't getting passed to my controller. I echoed out $_POST and it gave me an empty array. Any idea what I'm doing wrong? I'm using codeigniter 2 (which I know is very old now)

推荐答案

所以不能完全确定实际原因,但是codeigniter的CI核心可能存在一些错误,该错误无法解析使用fetch传递给控制器​​的数据.使用 FormData() axios ,我能够解决此问题.

So not completely sure about the actual reason but there might be some bug with the CI core of codeigniter which doesn't parse the data passed to controller using fetch. Using FormData() and axios I was able to resolve the issue.

 var postData = new FormData();
 postData.append('testdata', 123);
 axios.post('myurl/mycontroller', postData).then(function(response){
     console.log("success:", response);
 }).catch(function(error){
     console.log("error:", error);
 });

这篇关于无法访问控制器中的提取帖子数据:Codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆