从codeigniter中获取外部表单中的JSON数据

时间:2014-09-10 10:31:13

标签: php json codeigniter

我有一个外部网络表单,可以将数据发布到我的控制器网址。数据以JSON字符串发送。

我需要做的是获取JSON字符串中的各个值并将它们添加到我的数据库中。但是,我在获取发布的值并解码它们时遇到了一些麻烦。

这是我尝试过的代码 - 非常感谢任何帮助谢谢。

public function index() { 
    $this->load->view('lead');
    $form_data = array(
    'firstname' => json_decode($this->input->post('first_name')),
    'lastname' =>json_decode($this->input->post('last_name')),
    'number' =>json_decode($this->input->post('phone_number')),
    'email' =>json_decode($this->input->post('email')),
    'suburb' =>json_decode($this->input->post('suburb')),
    'state' =>json_decode($this->input->post('state')),
    'enquiry' =>json_decode($this->input->post('enquiry'))
);

// run insert model to write data to db

if ($this->AddLeadModel->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db { //Do something if successful }

3 个答案:

答案 0 :(得分:0)

不要对各个表单字段进行json_decode。 你必须使用json json_decode传入的字段, 然后使用数组数据再次填充表单。

简单来说:你从字段填充到JS端的数组中,然后json_encoded用于传输到服务器。现在你需要扩展json以恢复数组。

// decode the incomning json 
// you get an array
$json_array = json_decode($this->input->post('the_form_field_name_of_your_json'));

// now assign the array data to the form
$form_data = array(
    'firstname' => $json_array['first_name'],
    ...
    ...
);

答案 1 :(得分:0)

试试这个:

$json = file_get_contents('php://input');
$input_data = json_decode($json, TRUE);

答案 2 :(得分:0)

将通过示例解释(此工作):

// Assuming the values you are getting via POST

$first_name = '{"first_name" : "Parag"}';
$last_name = '{"last_name" : "Tyagi"}';
$phone_number = '{"phone_number" : "9999999999"}';

$form_data['firstname'] = json_decode($first_name, TRUE)['first_name'];
$form_data['lastname'] = json_decode($last_name, TRUE)['last_name'];
$form_data['number'] = json_decode($phone_number, TRUE)['phone_number'];

print_r($form_data);


DEMO:

http://3v4l.org/dmIrr


现在查看下面(这是工作)

// Assuming the values you are getting via POST

$first_name = "{'first_name' : 'Parag'}";
$last_name = "{'last_name' : 'Tyagi'}";
$phone_number = "{'phone_number' : '9999999999'}";

$form_data['firstname'] = json_decode($first_name, TRUE)['first_name'];
$form_data['lastname'] = json_decode($last_name, TRUE)['last_name'];
$form_data['number'] = json_decode($phone_number, TRUE)['phone_number'];

print_r($form_data);


DEMO:

http://3v4l.org/MeJoU


说明:

如果您将帖子中的JSON传递给json_decode,则会失败。有效的JSON字符串包含引用键。因此,请检查您的案例并查看您获得JSON的格式(通过POST)。