简体   繁体   English

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

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

I am using Select2 jquery plugin and I can't get results with json. 我正在使用Select2 jquery插件,我无法使用json获得结果。 When looking json response in browser it looks ok. 在浏览器中查看json响应时看起来没问题。 Like this for example: 像这样例如:

[{
        "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&_=1417999511783 but 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 未捕获的TypeError:无法读取未定义的属性“长度”

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? 代码中是否有错误?

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" 第二,看起来你试图从名为“结果”的json响应中调用一个属性

if that was the case your json should look like this, note that family is now text due to the change above: 如果是这种情况你的json应该是这样的,请注意由于上面的更改,系列现在是文本:

{
"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);

?>

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

you need to define the text property on the results 您需要在结果上定义text属性

and you might need to add formatResult and 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; }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM