无法从JSON字符串中选择特定的ID

时间:2015-03-31 18:29:39

标签: javascript jquery json

所以我试图建立一个带有一些客户信息的管理页面,我遇到了这个问题,我无法从客户端选择ID来显示他的所有信息一个单独的页面。

基本上,在第一页site.com/client我有一个包含所有客户的小桌子,当我点击按钮进行可视化时,我会转到site.com/det_client&cliId=3我所在的页面所有信息。

此信息位于JSON文件中,每个客户端都有一个唯一的ID。这个ID正在从第一页发送到第二页,并且我正在使用jquery获取此数据。直到这一部分没问题。我可以做一切,并从客户端获得正确的ID

当我需要使用来自特定ID的所有信息编写新表时,问题就开始了。我试着看一下(在stackoverflow中),但我找到的解决方案给了我错误。这是我使用的代码:

$(document).ready(function() {
    var url = "data/c_fisico.json";
    var cli; //getting the client id from the url. rest of the code is in other page

    $.getJSON( url, function() {
        function findId(url, idToLookFor) {
            var categoryArray = url.aaData;
            for (var i = 0; i < categoryArray.length; i++) {
                if (categoryArray[i].cd == idToLookFor) {
                    return(categoryArray[i].id);
                }
            }
        }
    });

    var item = findId(url, cli),
        table = JSON.parse(item);

    //there is more data, but i made it smaller
    $.getJSON(table, function (response){
        var write;
        $.each (response, function (index, table) {
            write += '<tr><td>Cod</td><td>' + table.id + '</td></tr><tr><td>Name</td><td>' + table.nm_cliente + '</td></tr><tr><td>cpf</td><td>' + table.cpf + '</td></tr>';
        }); //end each
        $('#TableTest').html(write);
    }); //end getJSON

});

我遇到的错误是:Uncaught ReferenceError: findId is not defined

这是我的JSON的一个例子:

{
    "aaData": [
        {
            "id":0,
            "cd":"C-0001",
            "nm_cliente":"John",
            "cpf":"000.111.222-33",
            "nm_pai":"Nome Completo",
            "nm_mae":"Nome Completo",
            "tel":"00-9966-6699",
            "cidade":"city",
            "estado":"estate"
        },
        //rest of my code here...
    ]
}

所以,基本上,我需要的是从客户端获取具有相同ID的URL的所有信息,然后将其写在页面上以显示该特定客户端的所有详细信息。

3 个答案:

答案 0 :(得分:2)

您的问题在于您的函数范围:findId()是在传递给jQuery.getJSON()的回调中定义的,而不是在$(document).ready()回调中。

编辑:这应该大致是您尝试做的事情:

$(document).ready(function() {
  var url = "data/c_fisico.json";
  var cli; //getting the client id from the url. rest of the code is in other page

  $.getJSON(url, function(data) {
    var rows = '';
    data.aaData.forEach(function(aa) {
      rows += '<tr><td>Code</td><td>' + aa.cd + '</td></tr>' +
        '<tr><td>Name</td><td>' + aa.nm_cliente + '</td></tr>' +
        '<tr><td>cpf</td><td>' + aa.cpf + '</td></tr>';
    });
    $('#mytable').html(rows);
  });
});

我不是那种直接构建HTML的忠实粉丝(通常像ReactJS,或者只是将dom视为最坏的情况),但这就是你之前所拥有的,所以我&#39;我保持同样的方法。

答案 1 :(得分:1)

您需要将代码放在$.getJSON的回调中(并且实际上不需要函数findId)。否则,您需要实现一个回调函数(即,请求获取数据,然后async方法在完成后调用外部函数)。

如果您只需要加载一个ID,那么就像......

$(document).ready(function() {
    var url = "data/c_fisico.json";
    var cli; //getting the client id from the url. rest of the code is in other page

    $.getJSON( url, function(json_data) {
        var categoryArray = json_data.aaData;
        for (var i = 0; i < categoryArray.length; i++) {
            if (categoryArray[i].cd == cli) {
                writeItem(categoryArray[i]);  //Pass the matching object to writeItem.
                return;
            }
        }
    }); 
});

function writeItem(item) {
    //"item" has already been parsed to an object, it's no longer a JSON string.
    var write += '<tr><td>Cod</td><td>' + item.cd + '</td></tr><tr><td>Name</td><td>' + item.nm_cliente + '</td></tr><tr><td>cpf</td><td>' + item.cpf + '</td></tr>';
    $('#mytable').html(write);
}

如果您需要编写多行(多个ID,可能是通过按钮点击)而需要更新每次调用的数据集,例如......

var my_data = null;

$(document).ready(function() {
    var url = "data/c_fisico.json";

    //You should add error handling in here, so you know if the JSON file wasn't available.
    $.getJSON( url, function(json_data) {
        my_data = json_data.aaData;
        $("#some_button").attr("disabled", false);  //JSON data has loaded, so enable our button.
    });

    $("#some_button").attr("disabled", true);  //Disable our button so the user can't click it until JSON is loaded.
    $("#some_button").on("click", function() {
        var id = //Figure out what ID you want to load here.

        writeItem(id);  //Call the write function.
    });
});

function findId(id) {
    if (my_data === null) { return null; }  //JSON hasn't been retrieved yet, so we can't find anything.

    for (var i = 0; i < my_data.length; i++) {
        if (my_data[i].cd == id) {
            return my_data[i];
        }
    }

    return null;  //The requested ID wasn't found.
}



function writeItem(id) {
    var item = findId(id);
    if (item === null) {
        //The ID wasn't found or JSON isn't available.
        //Show error message or whatever you'd like.
        return;
    }

    var write = '<tr><td>Cod</td><td>' + item.cd + '</td></tr><tr><td>Name</td><td>' + item.nm_cliente + '</td></tr><tr><td>cpf</td><td>' + item.cpf + '</td></tr>';
    $('#mytable').append(write);  //Appends to existing table data.
}

最后,如果您需要加载多个ID,还要从数据源时间重新加载,就像...

var busy = false;


$(document).ready(function() {
    var url = "data/c_fisico.json";

    //You should add error handling in here, so you know if the JSON file wasn't available.
    $.getJSON( url, function(json_data) {
        my_data = json_data.aaData;
        $("#some_button").attr("disabled", false);  //JSON data has loaded, so enable our button.
    });

    $("#some_button").on("click", function() {
        var id = //Figure out what ID you want to load here.

        findId(id, writeItem);  //Call the find function and tell it to call the write function when done.
    });
});


function findId(id, callback) {
    if (busy) { return; }  //Don't call again if we're already in the process of another call.
    busy = true;

    $.getJSON( url, function(json_data) {
        var categories = json_data.aaData;
        for (var i = 0; i < categories.length; i++) {
            if (categories[i].cd == id) {
                //Item was found, so pass the object to our callback.
                callback(categories[i]);
                busy = false;  //You should also set busy = false if the getJSON call fails.
                return;
            }
        }

        //ID wasn't found.  Error message.
        busy = false;  //You should also set busy = false if the getJSON call fails.
    });
}


function writeItem(item) {
    //Gets called by findId as a callback function.

    var write = '<tr><td>Cod</td><td>' + item.cd + '</td></tr><tr><td>Name</td><td>' + item.nm_cliente + '</td></tr><tr><td>cpf</td><td>' + item.cpf + '</td></tr>';
    $('#mytable').append(write);  //Appends to existing table data.
}

请注意,示例中未处理的错误情况。我会把它留给你和你的实施!

答案 2 :(得分:0)

http://www.jinqJs.com使用开源项目jinqJs,你可以这样做。

var result = jinqJs().from('http://....').where('id = ' + cli).select();