Select2.js错误:无法读取未定义的属性“长度”

我正在使用Select2 jquery插件,我无法用json获得结果。 在浏览器中查看json响应时看起来没问题。 像这样举例如:

[{ "id" : "50", "family" : "Portulacaceae " }, { "id" : "76", "family" : "Styracaceae " }, { "id" : "137", "family" : "Dipsacaceae" } ] 

在这种情况下使用ajax调用的URL是: http://localhost/webpage/json_family.php?term=acac&_=1417999511783但是我无法在select2输入中得到结果,控制台说:

未捕获的TypeError:无法读取未定义的属性“长度”

这是代码:
HTML

  

JS

 $("#select2_family").select2({ minimumInputLength: 3, ajax: { url: "json_family.php", dataType: 'json', data: function (term) { return { term: term, }; }, results: function (data) { return { results: data.results }; } } }); 

PHP

 $myArray = array(); if ($result = $mysqli->query("SELECT id,family FROM family WHERE family LIKE '%$term%'")) { $tempArray = array(); while($row = $result->fetch_object()) { $tempArray = $row; array_push($myArray, $tempArray); } echo json_encode($myArray); } 

代码中是否有错误?

好的,我的示例在我的测试服务器上工作,请执行以下操作

将您的查询更改为此,更改了一些名称以便于阅读,但应该是相同的function,重要的部分是在查询中添加“AS TEXT”

 $query = $mysqli->query("SELECT id, family AS text FROM family WHERE family LIKE '%$term%'")); while ($row = mysql_fetch_assoc($query)) { $return[] = $row; } echo json_encode($return); 

第二,看起来你试图从名为“结果”的json响应中调用一个属性

如果是这种情况你的json应该是这样的,请注意由于上面的更改,系列现在是文本:

 { "results": [ { "id": "50", "text": "Portulacaceae " }, { "id": "76", "text": "Styracaceae " }, { "id": "137", "text": "Dipsacaceae" } ] } 

但是您的php不会创建属性结果,因此请更改结果函数以删除.results属性调用

  results: function (data) { return { results: data }; } 

我使用的最终代码(注意我没有逃避/清理$ _GET [term]或将其绑定到查询,建议你这样做)如果你仍然有问题我可以发送一个链接到我的网站示例

           

PHP

 connect($host, $user, $password, $db_name); } catch (Exception $e) { die($e->getMessage()); } $term = $_GET['term']; if (!$term){ $sub = $yog->query("SELECT id, family AS text FROM family"); } else { $sub = $yog->query("SELECT id, family AS text FROM family where family like '%$term%'"); } while ($row = mysql_fetch_assoc($sub)) { $return[] = $row; } echo json_encode($return); ?> 

注意:只是刺它。 突然发生了什么。

你的json没有财产结果,所以试试吧。

 $("#select2_family").select2({ minimumInputLength: 3, ajax: { url: "json_family.php", dataType: 'json', data: function (term) { return { term: term, }; }, results: function (data) { // CHANGED return { results: data }; } } }); 

更改了查询 – 看看这是否有帮助

 $myArray = array(); // here if ($result = $mysqli->query("SELECT id, family AS text FROM family WHERE family LIKE '%$term%'")) { $tempArray = array(); while($row = $result->fetch_object()) { $tempArray = $row; array_push($myArray, $tempArray); } echo json_encode($myArray); } 

您需要在结果上定义text属性

您可能需要添加formatResultformatSelection

 $("#select2_family").select2({ minimumInputLength: 3, ajax: { url: "json_family.php", dataType: 'json', data: function (term) { return { term: term, }; }, results: function (data) {return { results: data, text: 'family'}; }, formatResult: function(item) { return item.family; }, formatSelection: function(item) { return item.family; } } });