在ajax中获取json值

时间:2015-07-17 13:20:28

标签: jquery json

我在ajax中以json的形式返回值,我想检查返回值。但它警告未定义。请帮我解决这个问题。

Json值:

[{"ProjectID":10,"FileID":343,"Data":Sample},{"ProjectID":11,"FileID":344,"Data":Sample1}].

JS功能:

function Load() {
    var i;

    $.ajax({
        type: "POST",
        url: "Search.aspx/Load",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {

            var data = $.parseJSON(r.d);
             var Test= r.d.ProjectID;//undefined
            for (i = 0; i < r.d.length; i++) {

                paramList = "{'Data':'" + data.Data + "'}";
                if (paramList == "Sample") {
                    alert();
                }
            }
        }
    });
}

2 个答案:

答案 0 :(得分:0)

编辑:完整的代码如下:

function Load() { 
$.ajax({
    type: "POST",
    url: "Search.aspx/Load",
    data: "",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (r) {
        var data = $.parseJSON(r.d);

        $.each(data, function(index, item) {
            var test = item.ProjectID;

            var dataItem = $.parseJSON("{'Data':'" + item.Data + "'}");
            if (dataItem.Data == "Sample") {
                alert("This works");
            }
        });
    }
});

}

答案 1 :(得分:0)

的结果
$.parseJSON(r.d) 

是一个数组。要访问第i个记录的ProjectID(在循环内),请使用Load函数的修改版本:

function Load() {
        var i;

        $.ajax({
            type: "POST",
            url: "Search.aspx/Load",
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {

                var data = $.parseJSON(r.d);

                for (i = 0; i < data.length; i++) {
                    var test = data[i].ProjectID;
                    paramList = "{'Data':'" + data[i].Data + "'}";
                    if (paramList == "Sample") {
                        alert();
                    }
                }
            }
        });

    }