在Codeigniter控制器中处理JSON数据 [英] Handling JSON data in Codeigniter Controller

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

问题描述

我在通过GET请求从JQuery发送JSON数据时遇到问题.这是我的jQuery,用于使用GET发送数据.

I have a problem to send the JSON data from JQuery with GET request. This is my JQuery to send the data with GET.

    var xhr = new XMLHttpRequest();
    var url = "http://example.com/share/new?data=" + JSON.stringify({"id": "1", "type": "new", "data": "testabcd"});
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
        }
    };
    xhr.send();

这在我的控制器文件中.

This is in my Controller file.

    public function share()
    {
        header('Content-type: application/json');

        $Data = json_decode($_GET["data"]);

        $data_share = array(
            'id' => $Data['id'],
            'type' => $Data['type'],
            'data' => $Data['data']);

        $this->db->insert('mytable', $data_share);

        return "200";
    }

问题在于Controller中没有内容抢劫,并且insert查询未插入任何内容.如何解决这个问题?也许我在代码中做错了什么?谢谢你.

The problem is nothing grab in the Controller and the insert query doesn't insert anything. How to fix this problem ? Maybe I do something wrong in my code ? Thank you before.

推荐答案

当您将json数据发送到php时,它的输入不在$_POST$_GET它的在php://input strem中;

when you send json data to php its in doesn't come in $_POST or $_GET its in php://input strem;

您向wj发送的ajax请求不是jQuery的核心js,这很好,但它相当不灵活,并且倾向于在其他浏览器中中断.我只是使用了非常灵活且跨浏览器的ajax的jQuery版本.

the ajax request u send ws not jQuery its core js, which is good but its quite unflexible and tends to break in different browser. i just used the jQuery version of the ajax which is very flexible and cross-browser as well.

尝试一下: JS:

$.ajax({
      method:'POST',
      contentType:'application/json',
      url:'http://example.com/share/new',
      data: JSON.stringify({"id": "1", "type": "new", "data": "testabcd"}),
      success:function(response){
       console.log(response);
      }

   });

PHP:

public function reservation()
{

    $Data = json_decode(file_get_contents('php://input'), true);

    $data_share = array(
        'id' => $Data['id'],
        'type' => $Data['type'],
        'data' => $Data['data']);

    $this->db->insert('mytable', $data_share);

    return "200";
}

这篇关于在Codeigniter控制器中处理JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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