機能しているフィドルがありますが、オートコンプリートでブラウザーに何も表示されません。フィドルはここで見ることができます: Working Fiddle
HTML には、テスト用の入力要素が 1 つあります。
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type ="text/javascript" src="myScripts.js"></script>
<script type ="text/javascript" src="jquery.csv-0.71.js"></script>
<script type ="text/javascript" src="csvToArray.v2.1.js"></script>
</head>
<body>
<div data-role="page" id="main">
<div data-role="header">
<h1>Test</h1>
</div>
<div id="contentDiv" data-role="content">
<input type="text" id="food" placeholder="Type (First Name) Here" />
</div>
</div>
</body>
私の JavaScript では、ファイルからテキストを読み取って json 変数を初期化しています。json 変数のアラートを表示して、初期化が成功したことをテストしました。そのjson変数をオートコンプリートのソースとして使用しようとしています。以下では、問題を絞り込むために json 変数の初期化をハードコーディングして、javascript を単純化しました。
var jsonVersion =
[{"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"}];
$('#food').autocomplete({
source: jsonVersion,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
これがフィドルでは機能するのにブラウザでは機能しない理由は何ですか? ブラウザ エラーは発生しません。テキストボックスに入力しても何も表示されません。
編集
おそらく、jsonVersion にデータを入力する方法に問題があるのかもしれませんが、「alert」で jsonVersion を出力すると正しく表示されます。ここで私が間違っていることについてのアドバイスをいただければ幸いです。これがJavaScriptファイル全体です。「データ」は配列の配列であり、これらの各配列をループしてオブジェクトを作成し、次にオブジェクトの配列を作成しています。次に、stringify を使用してオブジェクトの配列を json に変換します。
$(function ($) {
var jsonVersion;
var arrayOfObjects;
$.ajax({
type: "GET",
url: "test.js",
dataType: "text",
success: function(data) {
data = $.csv.toArrays(data);
arrayOfObjects = new Array();
for(var i=1; i<data.length; i++)//skipping over header
{
var foodObject = new Object();
foodObject.label = 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);
alert(jsonVersion);
}
});
$('#food').autocomplete({
source: jsonVersion,
select: function (event, ui) {
selectedObj = ui.item;
alert("selected object=" + selectedObj.value);
},
minLength: 1
});
})