0

我有一个 JSON 对象数组,看起来像:

jsonObject=      
[{"description":"mac and cheese", "servingSize":"1 cup", "calories":"500"},
 {"description":"slice of pizza", "servingSize":"1 slice", "calories":"400"},
 {"description":"oreo cookie", "servingSize":"1 cookie", "calories":"100"},
 {"description":"salad", "servingSize":"1 cup", "calories":"50"},
 {"description":"apple", "servingSize":"1 apple", "calories":"70"}]

我正在尝试使用 jsonObject 的描述字段创建一个自动完成文本框。我尝试了以下代码(在名为“food”的文本框上),它不显示任何内容:

$('#food').autocomplete({source:jsonObject,
                        select: function(event, ui) {
                                       selectedObj = ui.item;
                                       alert("selected object="+selectedObj.value);},
                        minLength:1
                    });

我还尝试使用来自 jsonObject 的描述创建一个单独的标签/值对数组,但仍然没有显示任何内容。谁能看到我错过了什么?

我希望保持 jsonObject 的完整,因为我最终试图访问与所选食物“描述”相关的份量和卡路里。

编辑:这是完整的代码。也许这将有助于找到问题...

var jsonVersion;

$(document).ready(function($){
$.ajax({
    type: "GET",
    url: "test.js",
    dataType: "text",
    success: function(data) {
                                data = $.csv.toArrays(data);
                                var arrayOfObjects = new Array();

                                for(var i=1; i<data.length; i++)//skipping over header
                                {
                                    var foodObject = new Object();
                                    foodObject.number = data[i][0];
                                    foodObject.description = data[i][1];
                                    foodObject.weight = data[i][2];
                                    foodObject.servingSize = data[i][3];
                                    foodObject.calories = data[i][4];
                                    arrayOfObjects.push(foodObject);
                                }
                                jsonVersion = JSON.stringify(arrayOfObjects);   

                            }
 });

});

$('#food').autocomplete({source:jsonVersion,
                          minLength:1
                          });
4

0 回答 0