用json验证 - ajax

时间:2012-04-03 15:25:56

标签: jquery ajax

如果我有这个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");
                   }
            }); 
        }); 
    });

感谢

4 个答案:

答案 0 :(得分: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 :(得分:1)

将响应字符串转换为Javascript对象是一个问题:

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

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

虽然您可以使用jQuery.getJSON功能,但可以省去一些麻烦

答案 2 :(得分:0)

检查您的回复是否是字符串而不是对象。然后你必须打电话

var obj = jQuery.parseJSON(data);

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

答案 3 :(得分: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。