简体   繁体   中英

How to loop through this JSON array on jQuery?

I have a two dimensional JSON array returned from a PHP script via a jQuery AJAX call. I have been browsing around trying to find out how to loop through each of the rows and display each entry within a div but I am very confused and unsure on how to do it in this particular case.

Here is an example of a JSON returned by the server:

{"location_id":"505","location_name":"University of the Arts London","location_type":"uni","location_num_listings":"22","location_num_users":"187","relevancy":"2"},
    {"location_id":"592","location_name":"London South Bank University","location_type":"uni","location_num_listings":"1","location_num_users":"1","relevancy":"2"},
    {"location_id":"591","location_name":"London Metropolitan University","location_type":"uni","location_num_listings":"47","location_num_users":"185","relevancy":"2"},
    {"location_id":"590","location_name":"University College London","location_type":"uni","location_num_listings":"29","location_num_users":"176","relevancy":"2"},
    {"location_id":"586","location_name":"St George's, University of London","location_type":"uni","location_num_listings":"9","location_num_users":"4","relevancy":"2"},

Here is my script so far:

<script type="text/javascript">
    $("#directory_search_input").keyup(function() {
        $("#directory_search_results").html('');
        var regionvalue = $(this).val();
        var jsonresult;
        var url = '<?php echo site_url('ajax/ajax_default/directory_search')?>';
        $.post(url,{input_val:regionvalue}, function(data) {
            var results = jQuery.parseJSON(data);
            $.each(results, function() {
                $.each(this, function(index, value) {
                    $("#directory_search_results").append(/*Append a new div for each row returned*/);
                });
            }); });

Example desired output:

Location ID: 505, Location Name: University of the Arts London

Location ID: 592, Location Name: London South Bank University

etc etc

var results = $.parseJSON(data);
$.each(results, function(i, result) {
    $("#directory_search_results").append('<div>Location ID: '+result.location_id+' Location Name: '+result.location_name+'</div>');
});

JSFiddle Example

$.each(data, function (index, value) {
            $("#SearchResults").append("<div>").append("Location Id  :" + value.location_id + ", Location Name : " + value.location_name ).append("\div");
});

assuming that your json object is named data , you can do the following:

$.each(data, function(key,value){
    //do all your code with key -> value pairs.
});

see an example here: http://jsfiddle.net/3muwm/

of course this uses the jQuery library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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