我正在Codeigniter中创建注册Web服务。我想以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
答案 0 :(得分:0)
返回json不需要视图。只需从控制器返回json_encode($ your_object)即可。
无论哪种方式,您正在寻找的方法是json_encode()。