如何从API加载数据?

时间:2020-03-20 18:29:29

标签: javascript ajax api

我制作了这个JavaScript(JQuery)来从API调用中加载数据,但是它给了我undefined。看起来是这样:

$(document).ready(function(){
    //Autocomplete for Person
    $(function() {
        $.ajax({
            type: 'GET',
            url: urlReq+'/api/persons/1',
            success: function(response) {
                let modelArray = response;
                let dataModel = {};

                for (let i = 0; i < modelArray.length; i++) {
                    dataModel[modelArray[i].first_name] = null;
                    console.log('data is: '+modelArray[i].first_name);
                }

                $('input.autocomplete_person').autocomplete({
                    data: dataModel,
                });
            }
        });
    });
});

我的urlReq+'/api/persons/1'返回如下内容:

{"452":{"id":452,"reference":"20190528155926096","first_name":"John","middle_name":"Smith","third_name":null,"family_name":"Doe"}}

但是我的问题是我的控制台给了我这个:data is: undefined

2 个答案:

答案 0 :(得分:1)

 {"452":{"id":452,"reference":"20190528155926096","first_name":"John","middle_name":"Smith","third_name":null,"family_name":"Doe"}}

这不是一个数组,因此您无法对其进行迭代。

答案 1 :(得分:0)

您可以删除for循环并直接分配响应:

let firstName = response[0].first_name; // "John"