Laravel - 从json文件中获取数据作为数组

时间:2016-12-06 18:34:05

标签: javascript jquery arrays json laravel

Html:

<div id="suggestionsearch" class="form-group">
 <input id="searchinput" type="text" class="form-control typeahead" placeholder="Search...">
</div>

Php控制器:

public function searchlive(Request $request)
    {

        $term = $request->term;
        $productindex = Product::where('product_name', 'LIKE', '%' . $term . '%')->take(5)->get();
        $results = array();
        foreach ($productindex as $key => $value) {
            $results[]= ['id'=>$value->id, 'value'=>$value->product_name];
        }
        return Response()->json($results);
}

jquery(工作代码):

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);
  };
};

 var states = ['Alabama ma ma ma', 'Alaska', 'Arizona', 'Arkansas', 'California',
   'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
   'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
   'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
   'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
   'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
   'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
   'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
   'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
 ];

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

jquery(不工作):

...
...
$('#suggestionsearch #searchinput').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      name: 'states',
      source: substringMatcher('{!! URL::route('searchlive') !!}')
    });

我的问题是从控制器获取json结果作为数组。我不希望静态数组作为状态的例子,但作为我的控制器的结果是动态的。如何正确定义源? 它说(不工作jquery):

 `Uncaught TypeError: Cannot use 'in' operator to search for '27' in http://localhost:8000/search(…)`

0 个答案:

没有答案