Uncaught TypeError错误排查:Laravel数据适配jQuery Typeahead异常
解决jQuery Typeahead中“Uncaught TypeError: b.toLowerCase is not a function”错误
我之前也碰到过这个问题,一眼就能看出是数据源格式不匹配导致的——jQuery Typeahead组件默认期望你传入的是字符串数组,但你从Laravel接口拿到的是对象数组。组件内部会尝试对每个搜索项调用toLowerCase()做大小写不敏感匹配,可对象根本没有这个方法,自然就抛出这个错误了。
两种解决思路,选适合你的就行:
1. 前端处理数据,适配组件要求
在$.get的回调里,把返回的对象数组转换成组件能识别的格式。比如你想展示公司联系人的全名,就把每个对象的名字字段拼接成字符串,再传给process函数:
$('#getCompaniesForConnection').typeahead({ source: function (query, process) { return $.get('/all/companies', { query: query }, function (data) { // 把对象数组转成字符串数组(按需拼接字段) const companyLabels = data.map(company => `${company.firstname} ${company.middle_name} ${company.lastname}` ); return process(companyLabels); }); } });
如果需要在选中后获取公司的ID等额外信息,就稍微复杂点,先把对象转成带display/value字段的结构,再处理:
// 先在外部存一份原始数据,方便选中后查找 let allCompanies = []; $('#getCompaniesForConnection').typeahead({ source: function (query, process) { return $.get('/all/companies', { query: query }, function (data) { allCompanies = data; // 生成组件需要的显示文本数组 const displayTexts = data.map(company => `${company.firstname} ${company.middle_name} ${company.lastname}` ); return process(displayTexts); }); }, // 选中项后的回调,获取完整对象信息 afterSelect: function(selectedText) { const selectedCompany = allCompanies.find(company => `${company.firstname} ${company.middle_name} ${company.lastname}` === selectedText ); console.log('选中的公司ID:', selectedCompany.id); } });
2. 修改Laravel后端,直接返回字符串数组
如果前端只需要搜索展示文本,不需要额外的对象字段,那直接在后端处理好返回更省事:
$companies = \App\User::where('type', 'pet-salon') ->orWhere('type', 'veterinarian') ->get(['firstname', 'middle_name', 'lastname']) ->map(function($user) { // 拼接成前端需要的字符串格式 return $user->firstname . ' ' . $user->middle_name . ' ' . $user->lastname; }); return response()->json($companies);
这样前端拿到的就是纯字符串数组,直接传给process就不会有任何问题了。
内容的提问来源于stack exchange,提问作者Dip
相关产品推荐
相关产品推荐

