如何在codeigniter中将数据发布为json?

时间:2016-09-01 07:23:57

标签: json codeigniter

我必须在codeigniter中将数据发布为json对象格式。它怎么能成为可能。 我的模型函数如下:

public function signAction()
{
        $name=$this->input->post('name',TRUE);
        $dob=$this->input->post('dob',TRUE);
        $gender=$this->input->post('gender',TRUE);
        $country=$this->input->post('country',TRUE);
        $city=$this->input->post('city',TRUE);
        $mobile=$this->input->post('mobile',TRUE);
        $email=$this->input->post('email',TRUE);
        $password=$this->input->post('password',TRUE);

        $this->db->select("*");
        $this->db->where('email',$email);
        $this->db->or_where('mobile',$mobile);

        $query = $this->db->get('dr_signup');

        $value=$query->num_rows();
        if($value==0)
        {
            $sql = "INSERT INTO dr_signup (name,dob,gender,country,city,mobile,email,password) 
                VALUES(".$this->db->escape($name).",".$this->db->escape($dob).",".$this->db->escape($gender).",".$this->db->escape($country).",
                       ".$this->db->escape($city).",".$this->db->escape($mobile).",".$this->db->escape($email).",".$this->db->escape($password).")";
                $value1=$this->db->query($sql);
                $insert_id = $this->db->insert_id();

                $details = array(
              'status'=>'success', 
              'message'=>'registered sucessfully',
              'id' => $insert_id ,
              'name' => $name,
              'dob'=>$dob,
              'gender'=>$gender,
              'country'=>$country,
              'city'=>$city,
              'mobile'=>$mobile,
              'email'=>$email,

              );

                echo  json_encode($details);
        }
        else
        {

            $detail = array(
            'status'=>'unsuccess', 
            'message'=>'already registered',

    );

    echo  json_encode($detail); 
        }

}

我必须将数据发布为json格式。我的json对象看起来像:

{"name":"jon","dob":"1jan2015","gender":"male","country":"India","city":"Mumbai","mobile":"86064 70000","email":"sales@green.tech","password":"1234"}

我是新手。它怎么能成为可能。我应该在代码中做什么修改。提前感谢。

2 个答案:

答案 0 :(得分:1)

例如,你可以在$this->input->post('json_string',true);中获得json,你可以使用这样的代码..

$jsonstring = $this->input->post('json_string');
$json_data = json_decode($jsonstring,true); //remove true if you need object or keep it for array

$json_data将为您提供已发布的json字符串的键值,例如$json_data['name'] ...

答案 1 :(得分:0)

你试试这样

return json_encode($details); 

delete your code "echo  json_encode($details)"  

我认为它的工作