使用Jquery

时间:2018-05-09 03:42:24

标签: jquery

美好的一天如何使用jquery获取此ajax响应?这是我当前的jquery代码

    function fetch(select){
        if ($(select).val() !== null) {
            var rank= $("#rank");
            $.getJSON('{{route("json_style_rank")}}', {id: $(select).val()}, function(data) {
                $("#rank option").remove();
                $.each(data.ranks, function(){
                    rank.append('<option value="'+ this.id +'">'+ this.name +'</option>')
                });
                rank.select2().val(null).trigger('change');
            });
        }
    }

这是ajax响应

[,…]
0:{id: 118, organization_id: 6035, school_id: null, picture: "", name: "Hapkido", description: "Kicks",…}
created_at:"2017-05-22 15:34:32"
description:"Kicks"
id:118
name:"Hapkido"
organization_id:6035
picture:""
ranks:[,…]
0:{id: 561, style_id: 118, level: 1, name: "1st Dan ", type: "solid", tip_enabled: 0, tip_sequential: 1,…}
1:{id: 562, style_id: 118, level: 2, name: "1st Gup", type: "double", tip_enabled: 1, tip_sequential: 1,…}
2:{id: 563, style_id: 118, level: 3, name: "2nd Gup", type: "double", tip_enabled: 1, tip_sequential: 1,…}
3:{id: 564, style_id: 118, level: 4, name: "3rd Gup", type: "solid", tip_enabled: 1, tip_sequential: 1,…}
4:{id: 565, style_id: 118, level: 5, name: "4th Gup", type: "solid", tip_enabled: 1, tip_sequential: 0,…}
5:{id: 917, style_id: 118, level: 6, name: "5th Gup", type: "solid", tip_enabled: 0, tip_sequential: 1,…}
school_id:null
updated_at:"2017-05-22 15:34:32"

enter image description here

我想获得排名id和名称

1 个答案:

答案 0 :(得分:1)

试试这个。

function fetch(select){
    if ($(select).val() !== null) {
        var rank= $("#rank");
        $.getJSON('{{route("json_style_rank")}}', {id: $(select).val()}, function(data) {
            $("#rank option").remove();
            //Get and loop over only first element of the response array
            $.each(data[0].ranks, function(){
                rank.append('<option value="'+ this.id +'">'+ this.name +'</option>')
            });
            rank.select2().val(null).trigger('change');
        });
    }
}

<强>更新: 要迭代响应数组中的所有元素,您还需要一个$.each循环

$.each(data, function(){
    //Get and loop over only first element of the response array
    $.each(this.ranks, function(){
        rank.append('<option value="'+ this.id +'">'+ this.name +'</option>')
    });
});
相关问题