代码之家  ›  专栏  ›  技术社区  ›  Mubbasher Ahmed Qureshi

选择2 JS不显示来自AJAX的数据

  •  0
  • Mubbasher Ahmed Qureshi  · 技术社区  · 7 年前

    我试图使用select2 js最新版本获取ajax结果,但出现以下错误:

    jQuery。延迟异常:无法读取未定义的属性“results”
    TypeError:无法读取未定义的属性“results”

    我正在使用的jQuery版本: jquery-3.2.1。最小值

    我正在使用的引导版本: 4.

    这是我的代码:

    $(document).ready(function(){
        		$('#category').select2({
        			placeholder: 'Subjects',
        			minimumInputLength: 3,
        			allowClear: true,
        			ajax:{
        				url: "<?php echo base_url(); ?>library/ajax-categories",
        				dataType: "json",
        				delay: 250,
        				data: function(params)
        				{
        					return{
        						search: params.term,
        						type: 'public'
        					};
        				},
        				processResults: function(data, page)
        				{
        					var newResults = [];
    
        					$.each(data, function(index, item)
        					{
        						newResults.push({
        							id: item.CategoryID,
        							text: item.CategoryName
        						});
        					});
        					return
        					{
        						results: newResults
        					}
        				}
        			}
        		});
        	});
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <select class="select2 form-control" name="category[]" id="category" placeholder="Choose Subjects" multiple>
        </select>

    我从服务器端脚本得到的响应:

    [
     {"CategoryID":"1","CategoryName":"A Name"},
     {"CategoryID":"2","CategoryName":"B Name"},
     {"CategoryID":"3","CategoryName":"C Name"}
    ] 
    

    我将以下响应转换为select2模式,即“id,text”,正如您在我的JS代码中看到的那样。

    请帮助我解决这个错误。

    1 回复  |  直到 7 年前
        1
  •  2
  •   ztadic91    7 年前

    这看起来像是一个语法问题。从processResults函数重新格式化返回语句,如下所示。问题出在返回语句中。

      return {
          results: newResults,
      };
    

    JS引擎将您的语句转换为:

    return;
    {
       results: newResults 
    }
    

    其他信息 here here