Pergunta

I have a working connection between my json object and getJSON(). I can also sort the data i get once with this code, I sorted it on the 'name' field of the array and it works fine:

$.getJSON(url,function(json){ 
    function sortJson(a,b){
        return a.name > b.name? 1 : -1;
    }
    json.users.sort(sortJson);  
    $.each(json.users,function(i,row){ 
        $("#output").append(
            '<li>' + row.id + row.name + row.job + '</li>'
        );
    }); 
});

and this is my json array:

{"users":[
{"id":"1","name":"John","job":"worker"}
{"id":"2","name":"Mike","job":"innovator"}
{"id":"3","name":"Anna","job":"reader"}
]}

What I want is that when i click on a button the sortJson() should sort the users on another field like 'id' or 'job'. I did this:

function sortJsonField(x){
    var field = x;
    var url="http://localhost/api/users.php";
    $.getJSON(url,function(json){ 
        function sortJson(a,b){
            if(field == "id"){ return a.id > b.id? 1 : -1; }else
            if(field == "job"){ return a.job > b.job? 1 : -1; }else
            return a.name > b.name? 1 : -1;
        }
        json.users.sort(sortJson);  
        $.each(json.users,function(i,row){ 
            $("#output").append(
                '<li>' + row.id + row.name + row.job + '</li>'
            );
        }); 
    });
}

and it worked, now you should be wondering what my problem is. Here it is, every time I click on the button to execute sortJsonField('thefieldname'). It executes the whole $.getJSON, making a new connection with the url and communicating with the back-end. I don't want that, it's too slow and the workload will be heavy for the server. I want to get the json once and then sort the array afterwards(so actually only the $.each function i need to refresh). But it's not working.

Any ideas?

okay i modified the code and i think i'm really close:

<!DOCTYPE html><head>
<title>Users</title>
<script src="jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
    var url="http://192.168.247.86/X/users.php";
    var json =  { users: [] };
    //getting & storing
    $.getJSON(url,function(response){
        json = response;    
    });
    //sorting
    function sortJsonField(field){
        alert(field);
        function sortJson(a,b){
            if(field == "id"){ return a.id > b.id? 1 : -1; }else
            if(field == "job"){ return a.job > b.job? 1 : -1; }else
            return a.name > b.name? 1 : -1;
        }

        json.users.sort(sortJson);
        showJSON();
    };
    //showing
    function showJSON(){
        $.each(json.users,function(i,row){ 
            $("#output").append(
                '<li><em>' + row.id + '</em><br>' + row.name + '<br>' + row.job  + '</li>'
            );
        });
    };
});
</script>
</head>

<h1>Users</h1>
<button onClick="sortJsonField(Id)">Id</button>
<button onClick="sortJsonField('Name')">Name</button>
<button onClick="sortJsonField('Job')">Job</button>
<ul id="output"></ul>
</body>
</html>

and this is my json:

{"users":[{"id":"1","name":"John","job":"Worker"},{"id":"2","name":"Mike","job":"Reader"},{"id":"3","name":"Mary","job":"Writer"},{"id":"4","name":"Angelo","job":"Player"},{"id":"5","name":"Kevin","job":"Doctor"},{"id":"6","name":"Zidane","job":"Player"}]}

Got it working now

    <!DOCTYPE html>
<head>
<script src="jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
    var url="http://localhost/X/users.php";
    var json = new Array();
    //getter
    $.getJSON(url,function(data){
        json = data;
    }).done(function(){
        sortJsonField();
        $('#sortid').click(function(){
            sortJsonField("id");
        })
        $('#sortname').click(function(){
            sortJsonField("name");
        })
        $('#sortjob').click(function(){
            sortJsonField("job");
        })
    });

        function sortJsonField(field){
            function sortJson(a,b){
                if(field == "id"){ return a.id > b.id? 1 : -1; }else
                if(field == "job"){ return a.job > b.job? 1 : -1; }else
                return a.name > b.name? 1 : -1;
            }
            json.users.sort(sortJson);
            showJSON();
        };
        //shower
        function showJSON(){
            $('#output').empty();
            $.each(json.users,function(i,row){ 
                $("#output").append(
                    '<li><em>' + row.id + '</em><br>' + row.name + '<br>' + row.job + '</li>'
                );
            });
        };
        showJSON(); 
});
</script>
</head>
<body>
<button id="sortid">Id</button>
<button id="sortname">Name</button>
<button id="sortjob">Job</button>
    <div id="output"></div>
</body>
</html>
Foi útil?

Solução

Do this:

var json = { users: [] };
var url="http://localhost/api/users.php";
$.getJSON(url,function(response){
    json = response;
});

function sortJsonField(field){

    function sortJson(a,b){
        if(field == "id"){ return a.id > b.id? 1 : -1; }else
        if(field == "job"){ return a.job > b.job? 1 : -1; }else
        return a.name > b.name? 1 : -1;
    }

    // No need to assign this to a new array.
    json.users.sort(sortJson);

    showJSON();
};

function showJSON(){

    // May empty the ul/ol before doing this? up to you..
    $.each(json.users,function(i,row){ 
        $("#output").append(
            '<li>' + row.id + row.name + row.job + '</li>'
        );
    });

};

EDIT: Also, the JSON structure is slightly incorrect...

Change this:

{"users":[
{"id":"1","name":"John","job":"worker"}
{"id":"2","name":"Mike","job":"innovator"}
{"id":"3","name":"Anna","job":"reader"}
]}

....to this:

{"users":[
{"id":"1","name":"John","job":"worker"},     // <--- Do you see the commas here?
{"id":"2","name":"Mike","job":"innovator"},    // <--- and here?
{"id":"3","name":"Anna","job":"reader"}
]}

The objects are well-formed, but that is not a valid array, so javascript breaks. Modify it and it should all work.

P.S This is the url of the website I used to check your JSON structure: http://www.freeformatter.com/json-validator.html

Outras dicas

You need to create a variable that will store the JSON and use that once the request returns.

var jsonData;
$.getJSON(url,function(json){ 
      jsonData = json;
}); 

Now you can sort the data contained in jsonData.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top