2016-12-06 51 views
1

我的JavaScript以下和平:JSON字符串,但PHP變量打印空

$('.showEditForm').click(function() { 
    var webpagefileID = this.id; 
    if($('#editForm').css('display', 'none')) { 
     $('#editForm').css('display','block'); 
     $('#allFilesTable').css('display','none'); 
    }  
    $.post 
    ('http://localhost/myproject/Controllername/display_edit_record_form', { webpagefileID: webpagefileID }, function(result) { 

    });  
}); 

使用後,我打電話方法display_edit_record_form我笨控制器

這裏是在我笨控制器命名display_edit_record_form方法的代碼:

public function display_edit_record_form($webpagefileID) 
    { 
     $webpagefileID = $this->input->post('webpagefileID'); 
     $data['webpagefile'] = $this->Webpage_file_model->get($webpagefileID); 
     //$this->output->set_content_type('application/json'); 
     $this->output->set_output(json_encode($data['webpagefile'])); 
     echo json_encode(array("message" => $data['webpagefile'])); 
    } 

在PHP的看法,我想顯示與下面的代碼數據:

var_dump($message); 
echo "<br />"; 
$myarr1 = json_decode($message); 
print_r($myarr1); 
echo "<br />"; 
$myarr2 = json_decode($data['webpagefile']); 
print_r($myarr2); 
echo "<br />"; 
$myarr3 = json_decode($webpagefile); 
print_r($myarr3); 

我也得到一個NULL和2個空數組 在控制檯不過,我可以看到這一點:

現在,在控制檯,打開編輯表單的時候,我可以看到JSON字符串

{"message": 
{"webpagefileID":"10", 
"webpageID":"38", 
"webpagefileName":"New file", 
"webpagefileShowInRelatedFiles" :"1", 
.......continues..... 

我需要幫助,在視圖中我的PHP代碼來顯示這個字符串,所以我可以populoate我的表單字段有....

回答

1

的輸出errorCode這是因爲你從display_edit_record_form()方法得到的輸出是在ajax中接收到的。所以你的$message變量顯示爲空白。 你需要做的是收到來自post請求的數據後,使用jquery更新你的視圖。

$.post 
    ('http://localhost/myproject/Controllername/display_edit_record_form', { webpagefileID: webpagefileID }, function(result) { 
     result = $.parseJSON(result); 
     // considering you have a text field with id myID 
     $('#myID').val(result.message.webpagefileID); 
     // similarly you can add any of your returned values 
    }); 
+0

有沒有什麼辦法可以在視圖中獲得php數組的結果? – user2417624

+0

不是我所知道的。如果你想在視圖中使用php數組的結果,你必須調用你的控制器中的方法並將值傳遞給視圖。但在這種情況下,這不會是異步的權利? –

+0

是的,這不是我想要的。 – user2417624

0

json_decode()結果是null這意味着解析不成功(通常是因爲字符串enconding)。 你應該可以看到打印輸出json_last_error

+0

我打印最後一個錯誤時得到0。 – user2417624