php-jQueryオートコンプリートが最初の試行で機能しない
プログラムに動的オートコンプリートを実装しようとしました。最初の入力後は完全に機能しています。ただし、最初の試行の提案は表示されません。ただし、サーバーはオートコンプリートに必要なソースに応答しています。これが私のコードです。
$('.autocomplete').live('keyup', function(){
$this = $(this);
var search = $this.val();
$.ajax({
url:'/package/index/search/keyword/'+search+'/format/json',
async: false,
success: function(res){
//console.log(res.options);
//console.log(res.defined_ids);
staticObject = res.defined_ids;
$this.autocomplete({
source: res.options
});
}
});
});
サーバー側のコードは
$keyword = $this->_getParam('keyword');
$elementDetailModel = new Package_Model_ElementDetail();
$arr = $elementDetailModel->searchElementDetail($keyword);
$this->view->options = $arr['options']; // returns in the format array("test2","my new test", "night stay in delux room")
$this->view->defined_ids = $arr['defined_ids']; // returns in the format array(21::21=>"test2", 22::22=>"my new test", 24::24=>"night stay in delux room")
firebugでログに記録されたdefined_idsとオプションをコンソールすると、テキストフィールドに「t」と入力すると次の応答が返されました。
オプション:
["test2"、 "my new test"、"デラックスルームでの宿泊"]
defined_ids:
オブジェクト{21::21 = "test2"、22 :: 22 = "私の新しいテスト"、24 ::24="デラックスルームに宿泊"}
どんな助けでも評価できるでしょう。よろしくお願いします。
答え :
解決策:
ファイアバグから表示される形式は、JSONの形式ではありません。これは配列であり、インデックスを使用してアクセスされます。
出力を表示するときは、最初に配列を json_encode()
してから、表示してください。
たとえば、質問に関しては、最終的な配列は次のようになります
$array['options'] = array("test2", "my new test", "night stay in room");
//Then you should echo the encoded the array to json
echo json_encode($array);
次に、ビューがこのリクエストでオフになっていることを確認します。
答え :
解決策:
コンテキストのサーバー側を指定するのを忘れた可能性があります。コントローラの_init()
メソッドに、次を追加します:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('actionName', 'json')
->initContext();
そして、必ず actionName
をアクションコントローラー名に置き換えてください。
その後、 $this->view->options = $arr['options']
は自動的に有効なjson形式に変換されます。
AjaxContextの詳細については、マニュアルをご覧ください。
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。