2012-04-03 79 views
1

如果我有这样的JSON响应验证使用JSON - 阿贾克斯

{"error":"repeated"} 

为什么警报没有显示?它需要放在某个地方dataType: "json"

$(function() { 
     $("#box a").click(function() { 
      var selectedId = $(this).attr("class"); 

      $.post("new_list.php", { 
       id_user: <?php echo $id;?>, 
       id_list: selectedId 
      }, function (data) { 
        if(data.error == 'repeated') { 
         alert("error"); 
        } 
      }); 
     }); 
    }); 

感谢

回答

2

它不会,除非你告诉它自动解析它作为JSON。

$(function() { 
    $("#box a").click(function() { 
     var selectedId = $(this).attr("class"); 

     $.post("new_list.php", { 
      id_user: <?php echo $id;?>, 
      id_list: selectedId 
     }, function (data) { 
       if(data.error == 'repeated') { 
        alert("error"); 
       } 
     }, 
     "json"); //Here, add this as last parameter 
    }); 
}); 
1

这将是响应字符串转换成Javascript对象的问题:

function (data) { 
    // Parse the JSON 
    data = JSON.parse(data); 

    if(data.error == 'repeated') { 
     alert("error"); 
    } 
} 

虽然你可以只使用jQuery.getJSON函数来代替,节省自己的一些麻烦

0

检查您的回复是一个字符串而不是一个对象。然后,你必须调用

var obj = jQuery.parseJSON(data); 

并使用obj.error检查它是否是“重复”

0
$(function() { 
     $("#box a").click(function() { 
      var selectedId = $(this).attr("class"); 

      $.post("new_list.php", { 
       id_user: <?php echo $id;?>, 
       id_list: selectedId 
      }, function (data) { 
        if(data.error == 'repeated') { 
         alert("error"); 
        } 
      },dataType: "json"); 
     }); 
    }); 

下面的代码片断将让jQuery的知道你期待JSON。