2012-12-20 59 views
0

我想弄清楚如何運行一個if語句與此作爲返回的JSON數據。當出現錯誤時,我希望它找出是否有錯誤的用戶名或密碼輸入,並在錯誤類別後附加一個標籤以表明實際錯誤。所以下面的if語句需要找出它的數據錯誤是否是用戶名,然後放入錯誤而不是錯誤。如果語句與json數據

{"output_status":"Error","output_title":"Form Not Validated","output_message":"The form did not validate successfully!","error_messages":{"username":"This is not have an accepted value!"}} 

if (data.output_status == 'Error') 
{ 

    if (data.?) 
    {   
     $('#username').after('<label class="error">error</label>'); 
    } 
} 

編輯:

我「不太清楚是怎麼回事,但現在我得到的形式沒有得到提交由於某種原因通知

$('#login_form :input:visible').each(function() { 
var name = $(this).attr('name'); 
if (data.error_messages.name) 
    { 
     $(this).after('<label class="error">' + data.error_messages.name + '</label>'); 
    } 
}); 

public function submit() 
{ 
    $output_status = 'Notice'; 
    $output_title = 'Not Processed'; 
    $output_message = 'The request was unprocessed!'; 

    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username'); 
    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); 
    $this->form_validation->set_rules('remember', 'Remember Me', 'trim|xss_clean|integer'); 

    if ($this->form_validation->run() == TRUE) 
    { 

    } 
    else 
    { 
     $output_status = 'Error'; 
     $output_title = 'Form Not Validated'; 
     $output_message = 'The form did not validate successfully!'; 
    } 

    echo json_encode(array('output_status' => $output_status, 'output_title' => $output_title, 'output_message' => $output_message, 'error_messages' => $this->form_validation->error_array())); 
} 

public function check_username($str) 
{ 
    if (preg_match('#[a-z0-9]#', $str)) 
    { 
     return TRUE; 
    } 
    $this->form_validation->set_message('check_username', 'This is not have an accepted value!'); 
    return FALSE; 
} 

回答

3

嘗試:

if (data.error_messages['username']) 
{   
    $('#username').after('<label class="error">' + data.error_messages['username'] + '</label>'); 
} 

現在,作爲獎勵,你可以遍歷所有的輸入字段,做同樣的:

$('#form-id :input:visible').each(function() { 
    var id = $(this).attr('id'); 
    if (data.error_messages[id]) 
    {   
     $(this).after('<label class="error">' + data.error_messages[id] + '</label>'); 
    } 
}); 
+0

我該如何獲得該錯誤消息的價值,而不是「錯誤」。 –

+0

''('#username')。'('');' –

+0

查看更新的答案 –

1

您可以通過對象鍵訪問錯誤信息 - 在這種情況下,「用戶名」:

if(data.error_messages["username"]) // this return undefined if it doesn't exist 
{ 
    // code 
} 
1
if (data.output_status == 'Error') 
{ 

    if (data.error_messages.username) 
    {   
     $('#username').after('<label class="error">' + data.error_messages.username + '</label>'); 
    } 
} 

如果沒有用戶名錯誤,data.error_messages.username只會返回undefined。

+0

我將如何獲取錯誤消息的值,而不是「錯誤」。 –