如何在codeigniter中对帖子进行JSON解码


How to JSON decode the post in codeigniter

我使用codeigniter,必须使用jquery使用json编码,当我想给出数据并验证它们时,我有问题。我的代码是:

$this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="nNote nFailure hideit"><p>', '</p></div>');
        $this->form_validation->set_rules('Name', 'Name', 'trim|required|xss_clean');
        $this->form_validation->set_rules('Parent', 'Parent', 'required|xss_clean');
        $this->form_validation->set_rules('Language', 'Language', 'required|xss_clean');
        $this->form_validation->set_rules('Order', 'Order', 'required|xss_clean');
if ($this->form_validation->run())
{
 //do something here
}

我应该如何使用JSON处理post请求?

老实说,我不确定你在问什么,但如果你想用json回应,这真的很简单,PHP让我们很容易做到。

json_encode(array('jsonKey' => 'jsonValue', 'jsonKey2' => 'jsonValue2'));

只需使用您喜欢的机制(回声、输出缓冲区等)设置适当的标题和输出即可

编辑:如果你想反其道而行之(你的脚本中有JSON数据)

只需执行以下

$myGreatAssocArray = json_decode($jsonStringData);

然后,您得到了一个关联数组,可以很容易地从中获取数据,如下所示:

$firstJsonValue = $myGretAssocArray['jsonKey1'];

它真的非常方便(而且比Java:p容易得多)

不过,请记住,json_decode不仅仅会返回数组。如果JSON格式错误,将返回NULL,因此如果需要执行任何条件语句,请确保使用!==NULL或类似的东西。