2014-09-10 94 views
1

我有一个外部Web表单,它将数据发布到我的控制器URL。数据以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 } 
+0

请检查JSON字符串格式。检查下面的答案。 – 2014-09-10 12:09:15

回答

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'], 
    ... 
    ... 
); 
+0

这就是我一直在寻找的东西,需要一些修改,但像魅力一样工作。谢谢! – easye 2014-09-10 13:04:46

+0

欢迎您:) – 2014-09-10 13:09:54

0

试试这个:

$json = file_get_contents('php://input'); 
$input_data = json_decode($json, TRUE); 
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)。

+0

两者之间的(微妙的)区别是JSON字符串中使用双引号(''')和单引号(''')。 – Matthew 2014-09-10 11:29:31

+0

是的,这可能是其中一个原因OP没有得到它的解码值 – 2014-09-10 11:31:28

+0

这可能会起作用,但是我发现将表单序列化为json并传输该对象会更好,而不是将每个表单字段作为json传递。关键词:“jquery post form serialized” - var form_data = $(“#form”)。serialize(); - http://api.jquery.com/serializearray/。 – 2014-09-10 13:09:10