2014-09-10 123 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