2 番目のデータ ソースからの選択をオートコンプリート ドロップダウンに挿入しようとしています。1 番目と 2 番目のソース フェッチはどちらも ajax 経由です。オートコンプリートのドロップダウンに 2D ソース データを挿入するために機能する JSON 配列を作成し、ハード コードしました。jsonLint テストに合格します。形式は次のとおりです。
[{"label":"New York, Bronx, Bronx County, New York, United States","value":"Bronx, Bronx County, New York, United States"},
{"label":"New York, Brooklyn, Kings County, New York, United States","value":"Brooklyn, Kings County, New York, United States", }]
変数データをその型と形式に入れるためのコードを作成するのに大きな問題があります。データベースには現在、JSON 文字列が含まれています。PHP の json_encode() を使用して、ブラウザーに渡されるデータ オブジェクトを作成します。データベース エントリは変更できますが、現在は次のようになっています。
"label":"New York, Bronx, Bronx County, New York, United States","value":"Bronx, Bronx County, New York, United States"
1. JSON 文字列がオブジェクトに変更されず、2. 無関係な不明な文字が何らかの形で挿入されているようです。ただし、私は特に関数とオブジェクトの初心者です。ここに jQuery/Javascript と、さまざまな時点でのデータの状態に関するいくつかのコメントがあります。
var boroughData = function() {
$.ajax({
//normal stuff like url:, dataType:, etc. It works.
success: function (data){
boroughData = $.map( data, function (item){
//data is JSON, but info inside extra " ", like Object { boroughString=""label":"Dallas, Cockre..., Texas, United States""}
// # response like [{"boroughString":"\"label\":\"Dallas, Cockrell Hill, Dallas County, Texas, United States\", . . ."}]
return item.boroughString;//returns JSON strings, not objects, in an array
});
alert(jQuery.isArray(boroughData) + "|bD1"); //true
console.log(boroughData); //array containing JSON strings in red
} //closes success: for boroughData
}); //closes ajax for boroughData
}(); //closes boroughData and (); executes it
alert(jQuery.isArray(boroughData) + "|bD2"); //false
alert(boroughData + "|bD3"); //"label":"Dallas, Cockrell Hill, Texas", "value":"Dallas, Cockrell Hill, Texas","label":"Dallas, Downtown Dallas, Texas", "value":"Dallas, etc.
alert(JSON.parse(boroughData) + "|bD4");//SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
bD1 での isArray テストは true で、bD2 での isArray テストは false であることに注意してください。それらの間で発生する唯一のことは、関数と ajax を閉じることです。また、一見余分な " " マークを説明するハッシュ # マークのあるコメント行にも注意してください。
上記の最初のコード ボックスで示した形式で JSON 配列を出力する boroughData 関数を取得するにはどうすればよいですか? アドバイスを具体的かつコードにしてください。私は初心者で、一般的な指示にうまく従いません。