2017-01-07 19 views
1

phpから先読みにデータの配列を渡したいが、それが機能していない、私は間違っていることを知らない。私は他の質問をチェックしましたが、解決策を得ることができませんでした。私は、コンソール上の応答を表示してみました、それはphpで先制型にjsonデータを渡すことができません

PHP

$resp = array(); 
     $states = $this->cj_model->list_all_states(); 
     foreach($states as $row){ 
      $resp[] = $row['name']; 
     } 
     echo json_encode($resp); 

JS

var substringMatcher = function(strs) { 
    return function findMatches(q, cb) { 
     var matches, substringRegex; 

     // an array that will be populated with substring matches 
     matches = []; 

     // regex used to determine if a string contains the substring `q` 
     substrRegex = new RegExp(q, 'i'); 

     // iterate through the pool of strings and for any string that 
     // contains the substring `q`, add it to the `matches` array 
     $.each(strs, function(i, str) { 
      if (substrRegex.test(str)) { 
       matches.push(str); 
      } 
     }); 

     cb(matches); 
    }; 
}; 

AJAX

function get_states() 
    { 
     $.ajax({ 
      url: 'country/get_states/', 
      dataType: 'json', 
      type: 'get', 
      async: true, 
      success: function(response){ 
       return (response); 
      }, 
      error: function(jqxhr, textStatus, error){ 
       console.log(error); 
      } 
     }); 
    } 

    var states = get_states(); 

    $('.typeahead').typeahead({ 
      hint: true, 
      highlight: true, 
      minLength: 1 
     }, 
     { 
      name: 'states', 
      source: substringMatcher(states) 
     }); 

答えて

1

が問題となる先行入力フィールド内の文字列が、何の配列を表示しますあなたはajaxの成功関数に何かを返そうとしています。 この場合、非同期リクエストを行うAjaxが不可能です。 このようなコードを書く。

$.ajax({ 
      url: 'country/get_states/', 
      dataType: 'json', 
      type: 'get', 
      async: true, 
      success: function(response){ 
       $('.typeahead').typeahead({ 
        hint: true, 
        highlight: true, 
        minLength: 1 
        }, 
        { 
        name: 'states', 
        source: substringMatcher(states) 
       }); 
      }, 
      error: function(jqxhr, textStatus, error){ 
       console.log(error); 
      } 
     }); 
+0

主な鉱山は、サーバーの成功コールバックの後に先行入力を活性化することである –

+0

何それはコード 'ソースで使用されているAJAX呼び出しからの応答、およそ:substringMatcher(レスポンス)'病気(このおかげで – 4Jean

+0

単純な変更変数substringMatcherを試してみてください状態)with substringMatcher(応答) –

関連する問題