【问题标题】:Cannot get response in json format when creating webservice in codeigniter在 codeigniter 中创建 web 服务时无法获得 json 格式的响应
【发布时间】:2015-11-03 12:21:59
【问题描述】:

我正在 Codeigniter 中创建注册网络服务。我想获取json格式的响应,如果注册成功,则数据将以json格式返回,如果数据已经存在,则返回json响应。我对如何将值从控制器传递到视图并将其转换为 json 响应感到困惑。以下是我的代码:

控制器:

<?php

session_start(); //we need to start session in order to access it through CI

Class User_Signup extends CI_Controller {

public function __construct() {
parent::__construct();

// Load form helper library
$this->load->helper('form');

// Load form validation library
$this->load->library('form_validation');

// Load session library
$this->load->library('session');


// Load database
$this->load->model('signup_model');
}

public function registration($fname,$lname,$email) {
$data=array('first_name' => $fname,'last_name' => $lname,'email' => $email);
$result = $this->signup_model->registration_insert($data);
if ($result == TRUE) {
$this->load->view('signup_message',$data);
} else {
$this->load->view('signup_message',$data);
}
}
}

Signup_model(型号):

<?php

Class Signup_Model extends CI_Model {

// Insert registration data in database
public function registration_insert($data) {

// Query to check whether username already exist or not
$condition = "email =" . "'" . $data['email'] . "'";
$this->load->database();
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {

// Query to insert data in database
$this->db->insert('user', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}
}
?>

查看:

<?php

/* output in necessary format */
if ($format == 'json')
{
    //header('Content-type: application/json');

    echo str_replace('\/', '/', json_encode($posts));
} else
{
    header('Content-type: text/xml');
    echo '<posts>';
    foreach ($posts as $index => $success)
    {
        if (is_array($success))
        {
            foreach ($success as $key => $value)
            {
                echo '<', $key, '>';
                if (is_array($value))
                {
                    foreach ($value as $tag => $val)
                    {
                        echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
                    }
                }
                echo '</', $key, '>';
            }
        }
    }
    echo '</posts>';
} 

?>

http://localhost/MyProject/user_signup/registration/Amit/Kumar/amit

【问题讨论】:

  • 您的网络服务部分在哪里
  • Abdulla- 我是 codeigniter 的新手,你能告诉我如何使用 codeigniter 在 json 中生成响应,以便其他人可以使用它。

标签: php json web-services codeigniter codeigniter-2


【解决方案1】:

返回 json 不需要视图。直接从控制器返回 json_encode($your_object)。

不管怎样,你要找的方法是json_encode()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    相关资源
    最近更新 更多