简体   繁体   English

无法仅从通过php页面获取的json数据返回用户名

[英]Can't return only usernames from json data fetched through a php page

I am able to get json data from an external php page and print it on the JavaScript console. 我能够从外部php页面获取json数据并将其打印在JavaScript控制台上。 But these are in the form objects. 但这些都是形式对象。 The following is the data I recieved on my console: 以下是我在控制台上收到的数据:

[{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}]

How can I extract only username and turn it into an ordered list. 如何仅提取用户名并将其转换为有序列表。 (ol) (醇)

This is what I have done so far: 这是我到目前为止所做的:

$(document).ready(function (e) {
    $('#delete').click(function (e) {
        var jsonData = getResultsInJson(username);
        jsonData.success(function (data) {
            var output = "<ol>";
            for (var i in data) {
                output += "<li>" + data.username + "</li>";
            }
            output += "</ol>";
            $('#placeholder').html(data);
            console.log(data.username);
        });
    });
});

This is getResultsInJson(): 这是getResultsInJson():

function getResultsInJson(sql) {
    return $.ajax({
        url: 'commands.php',
        data: 'results=' + sql,
        dataType: 'json'
    });
}

when you use the for(x in y) format, x is the key, and y is the array or object. 当你使用for(x in y)格式时,x是键,y是数组或对象。 Since i is just the key, you need to use it as one: 由于我只是关键,你需要将它作为一个使用:

 for (var i in data) {
            output += "<li>" + data[i].username + "</li>";
        }

Do you need them in alphabetically? 你按字母顺序需要它们吗?

Try something like this: 尝试这样的事情:

$(document).ready(function() {

var json = [{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}];

    var usernames = new Array();
    $.each(json, function(index, object) {
       usernames[index] = object.username;
    });
    var sorted = usernames.sort();

    var output = '';
    $.each(sorted, function(index, value) {
         output += '<li>' + value + '</li>';
    });
     $('#placeholder').html('<ol>' + output + '</ol>');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM