简体   繁体   English

使用jQuery获取响应

[英]Fetching a response using Jquery

Good day how can I fetch this ajax response using jquery? 美好的一天,如何使用jquery提取此ajax响应? This is my current jquery code 这是我当前的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');
            });
        }
    }

and this is the ajax response 这是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"

在此处输入图片说明

I want to get the ranks id and name 我想获取等级ID和名称

Try this. 尝试这个。

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');
        });
    }
}

Update : To iterate over all the elements in the response array, you'll need one more $.each loop 更新 :要遍历响应数组中的所有元素,您将需要一个$.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>')
    });
});

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

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