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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27349882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:22:30  来源:igfitidea点击:

Select2.js error: Cannot read property 'length' of undefined

javascriptphpjqueryjsonjquery-select2

提问by jakob

I am using Select2 jquery plugin and I can't get results with json. When looking json response in browser it looks ok. Like this for example:

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

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

URL called with ajax in this case is: http://localhost/webpage/json_family.php?term=acac&_=1417999511783but I can't get that results in select2 input, console says:

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

Uncaught TypeError: Cannot read property 'length' of undefined

未捕获的类型错误:无法读取未定义的属性“长度”

Here is code:
html

这是代码:
html

<input type="hidden" id="select2_family" name="term" style="width:30%" />

js

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

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

Is there error in code?

代码有错误吗?

回答by Jay Rizzi

Ok, i have your example working on my test server, please do the following

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

change your query to this, changed a few names for readability but should be the same functionality, important part is addition of "AS TEXT" in query

将您的查询更改为此,更改了一些名称以提高可读性,但应该具有相同的功能,重要的部分是在查询中添加“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);

second, it looks like you are trying to call a property from the json response called "results"

其次,您似乎正在尝试从名为“results”的 json 响应中调用一个属性

if that was the case your json should look like this, note that family is now text due to the change above:

如果是这种情况,您的 json 应该如下所示,请注意,由于上述更改,family 现在是文本:

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

But your php does not create the property results, so change your results function to remove the .results property call

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

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

final code i used (note i did not escape/sanitize the $_GET[term] or bind it to the query, recommend you do so ) if you are still having issues i can send you a link to my site example

我使用的最终代码(注意我没有对 $_GET[term] 进行转义/清理或将其绑定到查询,建议您这样做)如果您仍有问题,我可以向您发送指向我的站点示例的链接

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
</head>
<script>
$(document).ready(function () {

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

});
</script>

<input type="hidden" id="select2_family" name="term" style="width:30%" />

</html>

php

php

<?

/*** connection strings ***/

// get the database singleton instance
$yog = MySqlDatabase::getInstance();

// connect
try {
    $yog->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);

?>

回答by Todd

Note: just a stab at it. Just what stuck out.

注意:只是刺一下。只是什么突出。

Your json has no property results, so try.

你的 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 };

   }

  }
});

changed the query -- see if this helps

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

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

回答by Nerdroid

you need to define the textproperty on the results

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

and you might need to add formatResultand formatSelection

你可能需要添加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; }
    }
});