2011-11-04 17 views
0

我在處理JavaScript中的json變量時遇到問題。javascript不處理所有返回的json變量

當我嘗試將數據發佈到php類,然後它應該使用JSON返回3個變量時出現問題,但Firebug + FirePHP告訴我JSON變量正確返回。然後,當我嘗試將它們中的每一個存儲在不同的變量中時(3個返回3個JavaScript變量中的json變量),我只是得到第一個參數,其他兩個都是NULL。

您可以在明年的JavaScript代碼,請參閱:

function UpdateContact(ID) 
{ 
    // get current Contact data 
    var full_name,email,mobile; 
    $.post("/Cards/index.php/Cont/GetContactInfo",{'id' : ID}, 
     function(data){ 
       full_name = data.full_name; 
       email = data.email; 
       mobile = data.mobile; 
        $("#dialog2-form").html(
    '<p class="validateTips">All form fields are required.</p>'+ 
    '<form>'+ 
    '<fieldset>'+ 
     '<label for="name">Name</label>'+ 
     '<input type="text" name="Updatefull_name" id="Updatefull_name" class="text ui-widget-content ui-corner-all" value="'+full_name+'" /><br />'+ 
     '<label for="email">Email</label>'+ 
     '<input type="text" name="Updateemail" id="Updateemail" value="" class="text ui-widget-content ui-corner-all" value="'+data.email+'"/><br />'+ 
       '<label for="email">Mobile</label>'+ 
     '<input type="text" name="Updatemobile" id="Updatemobile" value="" class="text ui-widget-content ui-corner-all" value="'+data.mobile+'"/><br />'+ 
    '<input type="hidden" id="UpdateContactID" value="'+ID+'"></fieldset>'+ 
    '</form>' 
); 
    $("#dialog2-form").dialog("open"); 
}, "json"); 
} 

就在full_name變量得到一個數值,但emailmobile變量沒有得到任何價值。

PHP函數是:

function GetContactInfo() 
{ 
    $Contact = $this->Contacts->GetContacByID($this->input->post('id')); 
    $data['full_name'] = $Contact->full_name; 
    $data['email'] = $Contact->email; 
    $data['mobile'] = $Contact->mobile; 
    echo json_encode($data); 
} 

注:我使用的CodeIgniter PHP框架我的XAMPP本地主機服務器上

+0

var_dump($ data)請 – Peter

回答

0

您需要檢查該字段存在使用前:

var field_to_read = some_default_value; 
if (typeof data['name_of_field'] !== 'undefined') { 
    field_to_read = data['name_of_field']; 
} 

我建議你使用類似於上面的構造來閱讀你的JSON數據。

+0

您應該與字符串「undefined」進行比較。 – alex

+0

我不覺得它有多容易! – user504363

+0

@alex,謝謝,我的錯字。固定。 –