最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to extract json data in an array using a loop? - Stack Overflow

programmeradmin3浏览0评论

Hello guys I have a problem. And I don't know how to solve it. I am a beginner in ajax processing. I hope you can help me.

I have an ajax data from the success. And I want to put this in an array. Because I want to put the json data in an options select box.

Here's my code:

In my controller I have this

$('#state').on('change',function(){

            var state_code = $('#state').val();

            var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';

            $.ajax({

                type: 'POST',
                url: city_url,
                data: '',
                dataType: 'json',
                async: false,
                success: function(i){

                    console.log(i)

                }

            });

        });

And here's the select box options that i need to fill using json data

<select id="city" name="city">
    <option value="">---Select City---</option>
</select>

Here's the json reponse

[{"id":"1054","name":"Altavas"},{"id":"1055","name":"Balete"},{"id":"1056","name":"Banga"},{"id":"1057","name":"Batan"},{"id":"1058","name":"Buruanga"},{"id":"1059","name":"Ibajay"},{"id":"1060","name":"Kalibo"},{"id":"1061","name":"Lezo"},{"id":"1062","name":"Libacao"},{"id":"1063","name":"Madalag"},{"id":"1064","name":"Makato"},{"id":"1065","name":"Malay"},{"id":"1066","name":"Malinao"},{"id":"1067","name":"Nabas"},{"id":"1068","name":"New Washington"},{"id":"1069","name":"Numancia"},{"id":"1070","name":"Tangalan"}]

In my console.log I have this:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
length: 12

proto: Array[0]

If I clicked the arrow in the objects I will get this:

Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
id: "1028"
name: "Butuan City"
__proto__: Object
1: Object
id: "1029"
name: "Buenavista"
__proto__: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
length: 12
__proto__: Array[0]

That's all guys. Thanks.

Hello guys I have a problem. And I don't know how to solve it. I am a beginner in ajax processing. I hope you can help me.

I have an ajax data from the success. And I want to put this in an array. Because I want to put the json data in an options select box.

Here's my code:

In my controller I have this

$('#state').on('change',function(){

            var state_code = $('#state').val();

            var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';

            $.ajax({

                type: 'POST',
                url: city_url,
                data: '',
                dataType: 'json',
                async: false,
                success: function(i){

                    console.log(i)

                }

            });

        });

And here's the select box options that i need to fill using json data

<select id="city" name="city">
    <option value="">---Select City---</option>
</select>

Here's the json reponse

[{"id":"1054","name":"Altavas"},{"id":"1055","name":"Balete"},{"id":"1056","name":"Banga"},{"id":"1057","name":"Batan"},{"id":"1058","name":"Buruanga"},{"id":"1059","name":"Ibajay"},{"id":"1060","name":"Kalibo"},{"id":"1061","name":"Lezo"},{"id":"1062","name":"Libacao"},{"id":"1063","name":"Madalag"},{"id":"1064","name":"Makato"},{"id":"1065","name":"Malay"},{"id":"1066","name":"Malinao"},{"id":"1067","name":"Nabas"},{"id":"1068","name":"New Washington"},{"id":"1069","name":"Numancia"},{"id":"1070","name":"Tangalan"}]

In my console.log I have this:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
length: 12

proto: Array[0]

If I clicked the arrow in the objects I will get this:

Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
id: "1028"
name: "Butuan City"
__proto__: Object
1: Object
id: "1029"
name: "Buenavista"
__proto__: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
length: 12
__proto__: Array[0]

That's all guys. Thanks.

Share Improve this question edited Nov 27, 2013 at 7:23 Jerielle asked Nov 27, 2013 at 6:59 JerielleJerielle 7,52029 gold badges103 silver badges168 bronze badges 2
  • 4 show your response data (json ) it will helpfull – Rituraj ratan Commented Nov 27, 2013 at 7:00
  • Ok I will update my post – Jerielle Commented Nov 27, 2013 at 7:00
Add a ment  | 

11 Answers 11

Reset to default 4

just replace

success: function(i){
    console.log(i)
}

with

success: function(data){
    $.each($.parseJSON(data),function(index,value){
        $('#city').append('<option value="'+value.id+'">'+value.name+'</option>');
    });
}

Your response is already an array. Just iterate over it using jQuery.each(i, function(index, item) {...})

use this -

$.each(i, function(key,val){

 $('#city').append("<option value='" + key + ">" + val + "</option>");

});
  function(i){

     $.each(i,function(index,value){ 
       $("#city").append("<option value='"+value.id+"'>"+value.name+"</option>")
     });
  }

Don't use append by this it every time append on select box first make a string then set full html in select-box it is fast then append

var str='';
$.each(i, function(index,value){
str +="<option value='"+value.id+"'>"+value.name+"</option>";


});
 $('#city').html(str);

I understand when you console.log(i); you get the right response. Now what you need to do, is to JSON.parse the object and then set it on the select option.

With my experince, thats the tricky part, because select option can not be auto set by html.

So here is what might be some usable code(if you want something to be prefixed).

$(document).ready(function () {
    var size =    $('select').children('option').length;
    for (i=0;i<size;i++)
    {
        if ( $('select').children('option')[i].value === resultingObj.whatever)
        {
             $('select').children('option')[i].selected=true;
        }
    }
});

Good luck

try something like this

    $.ajax({
           type: 'POST',
           url: city_url,
           data: '',
           dataType: 'json',
           async: false,
           success: function(response){
            var resp_length = response.length;
            var option = '';
            for(var i = 0; i< resp_length;i++){
                option += '<option value="'+response[i].id+'">'+response[i].name+'</option>';
            }
            $('#city').append(option);//Opertation on DOM only one time.
           }
       });

Use following script

$.ajax({
  ...
  ...
  success: function(response){
    var option = null;
    //iterate each json record
    $(response).each(function(index, record){

      //create option tag with value and record name
      option = $('<li>').attr('value', record.id).html(record.name);

      //append this option tag to select box
      $('#city').append(option);
    });
  }

});

parse first your json to object then use $.each

success: function(i){
    json = JSON.parse(i);
    $.each(json,function(index,value){
        $('#city').append('<option value="'+value.id+'">'+value.name+'</option>');
    });
}

From your code I modified it to do what you would like.

success: function(i)
{
var resultingObj = JSON.parse(i);

    for(var iterator = 0; iterator < resultingObj.length; iterator++)
    {
        //perform actions
        $('#city').append('<option value="' + resultingObj[iterator].id + '">' + resultingObj[iterator].name + '</option>');
    }
}

Try this-

var select=$('#city');
for (var j=0; j<i.length; j++)
{
   select.append('<option value="'+i[j].id+'">'+i[j].name+'</option>');
}
发布评论

评论列表(0)

  1. 暂无评论