0

小提琴:http: //jsfiddle.net/wy4wd/19/

我正在解析一个 json 对象,但它落入了 else 中,导致 html 出现Error在它应该出现的时候ID not found,我不知道为什么。

如果successis ,它工作正常1

JSON 由 post 请求返回,但出于提问目的,我在本地声明它。

$(document).ready(function() {
    var data = '{"success": "0","patient_cid": "0"}';
    var response = jQuery.parseJSON(data);

    if (response.success == 0) {
        if (response.patient_cid == 0) {            
            $('#resultpanel').html('<p>ID not found</p>');
        }
        if (response.patient_ambassador == 0) {                 
            $('#resultpanel').html('<p>ID found but not an ambassador</p>');
        }               
        if (response.soap_error == '1') {                   
            $('#resultpanel').html('<p>SOAP error</p>').fadeIn('slow');
        }                   
    }
    if (response.success == 1){
        $('#resultpanel').html('<p>success</p>').fadeIn('slow');
    }   
    else {              
        $('#resultpanel').html('<p>Error</p>').fadeIn('slow');
    }   
});
4

3 回答 3

2

它应该是

//... previous code here
else if (response.success == 1){
//... the rest of the code here

如果我理解正确的话。

否则将执行第一个错误解析,但替换为最后一个 else 语句中的代码。

于 2013-04-02T08:57:39.390 回答
1

它与 JSON 的解析无关,是if语句中的逻辑导致了这种情况。

面板实际上设置为“未找到 ID”一小会儿,但随后您将其替换为“错误”。

else你第一个处理的地方success == 0,并else if用来做一个条件链:

if (response.success == 0) {
    if (response.patient_cid == 0) {            
        $('#resultpanel').html('<p>ID not found</p>');
    }
    else if (response.patient_ambassador == 0) {                 
        $('#resultpanel').html('<p>ID found but not an ambassador</p>');
    }               
    else if (response.soap_error == '1') {                   
        $('#resultpanel').html('<p>SOAP error</p>').fadeIn('slow');
    }                   
    else {              
        $('#resultpanel').html('<p>Error</p>').fadeIn('slow');
    }
}
if (response.success == 1){
    $('#resultpanel').html('<p>success</p>').fadeIn('slow');
}   
于 2013-04-02T09:02:20.460 回答
1

您已将值设置为您想要的值,但随后被此行重置为 Error $('#resultpanel').html('<p>Error</p>').fadeIn('slow');

您应该了解 false-y 和 truth-y 在 javascript 中的工作原理:我会这样做:

$(document).ready(function() {
var data = '{"success": "0","patient_cid": "0"}',
    response = jQuery.parseJSON(data),
    message;

    if (response.success == '1') {
        message = 'success';
    }
    else {
        if (response.patient_cid == '0') {            
            message = 'ID not found';
        }
        else if (response.patient_ambassador == '0') {
            message = 'ID found but not an ambassador';                 
        }               
        else if (response.soap_error == '1') {
            message = 'SOAP error';                              
        }
        else {              
            message = 'Error';                              
        }   
    }   
    $('#resultpanel').html('<p>' + message + '</p>').fadeIn('slow');
});
于 2013-04-02T09:06:11.990 回答