在AJAX自动完成中处理JSON

时间:2017-01-23 09:22:04

标签: javascript jquery json ajax

嗨,我通常是一个不太熟悉jquery的后端人,但我想创建一个简单的UI来使用ajax自动完成来查询我的API服务,假设我有JSON返回如下

{ addresses": [
    {
        "id": "gmap_auto3961949943bb427782ca7b3d1df6c64f",
        "name": "819643",
        "secondary_name": "Singapore",
        "description": "Singapore 819643",
        "types": [
            "postal_code"
        ],
        "attributes": {
            "latitude": 1.355322,
            "longitude": 103.988337
        }
    },
    {
        "id": "gmap_autoc98babeabdf77fd2788871786fed14ef",
        "name": "819663",
        "secondary_name": "Singapore",
        "description": "Singapore 819663",
        "types": [
            "postal_code"
        ],
        "attributes": {
            "latitude": 1.356716,
            "longitude": 103.98651
        }
    },
]
}

所以我的目的是取名称&辅助名称作为标签,id作为值。我怎么做?下面是我的AJAX

$( function() {
    function log( message ) {
        $( "<div>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $( "#address" ).autocomplete({
        source: function( request, response ) {
            $.ajax( {
                url: "/address/autocomplete",
                data: {
                    q: request.term,
                    countryCode: "sg"
                },
                success: function( data ) {
                    var ParsedObject = $.parseJSON(data);
                    response($.map(ParsedObject.addresses, function (item) {
                        return {
                            label: item.name,
                            value: item.secondary_name
                        };

                    }))
                }
            });
        },

        minLength: 2,
        select: function( event, ui ) {
            log( "Selected: " + ui.item.name + ", " + ui.item.secondary_name );
        }
    });
});

提前致谢

1 个答案:

答案 0 :(得分:1)

success回调

success: function( data ) {
   var ParsedObject = $.parseJSON(data);
   response($.map(ParsedObject.addresses, function (item) {
       return {
           label: item.name + ":" + item.secondary_name, //any delimiter to separate name and secondary name
           value: item.id //taking id from result
       };
   }))
}

select回调

select: function( event, ui ) { //on selection of autocomplete dropdown
    console.log( "Selected: " + ui.item.label + ", " + ui.item.value); //prints Selected: name:secondary_name, id
    //you can do whatever you want with label and value here
}