Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获的TypeError:无法读取未定义json数据的属性“length”_Javascript_Typeahead.js - Fatal编程技术网

Javascript 未捕获的TypeError:无法读取未定义json数据的属性“length”

Javascript 未捕获的TypeError:无法读取未定义json数据的属性“length”,javascript,typeahead.js,Javascript,Typeahead.js,我正在编写typeahead.js脚本,但没有得到正确的响应,我尝试了很多方法,但都没有成功。 此url正在从php文件返回jason数据 var result = (function( ) { var val = document.getElementById('sel_fac').value; var city = document.getElementById('select_city').value; var query = document.getElement

我正在编写typeahead.js脚本,但没有得到正确的响应,我尝试了很多方法,但都没有成功。 此url正在从php文件返回jason数据

var result = (function( )
{
    var val = document.getElementById('sel_fac').value;
    var city = document.getElementById('select_city').value;
    var query = document.getElementById('typeaheadfield').value;
    var url = 'search.php?fac=' + val + '&city=' + city + '&key=' + query;
    console.log(url);
    makeRequest(url, function(data) {
        var data = JSON.parse(data.responseText);
        console.log(data);
        return data;
    });
    function makeRequest(url, callback) {
        var request;
        if (window.XMLHttpRequest) {
            request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
        } else {
            request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
        }
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                callback(request);
            }
        }
        request.open("GET", url, true);
        request.send();
    }
})();
// console.log(result);

var substringMatcher = function(strs) {
 console.log(strs);
    return function findMatches(q, cb) {
        var matches, substringRegex;
        //  console.log(strs);
        window.alert(strs);
        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
                window.alert(str);
                // console.log(str);    
            }
        });

        cb(matches);
    };
};
当我尝试使用jason数据时,会得到正确的结果

//var result1=[金氏健身房平南达尼、金氏健身房马罗·纳卡、金氏健身房坎伯、金氏健身房班德拉西区、金氏健身房坎迪瓦利东区、金氏健身房下帕雷尔区、金氏健身房瓦希、金氏健身房坎迪瓦利西区、金氏健身房穆伦西区、金氏健身房-莫纳健身中心私人有限公司、金氏健身房博里瓦利西区、金氏健身房吉尼亚·约翰里@金氏健身房、金氏健身房塔恩西区、金氏健身房Kh阿尔西路,黄金体育馆格兰特路W]

$(document).ready(function() {

    $('#typeaheadfield').typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
        limit: 10
    },
    {
        name: 'fac_name',
        source: substringMatcher(result)
    });
    window.alert(result);
    console.log(result ? result.length : 'result is null or undefined');
});

您的函数设置结果是异步的。它无法立即返回数据,因此在等待数据时,它会继续执行下面的代码。要防止这种情况,请使用回调:

$(document).ready(function() {

  var result = []; // <--------------------------Define the variable (empty array)

  (function() {
    /* ... */
    makeRequest(url, function(data) {
      var data = JSON.parse(data.responseText);
      //return data;  <--------------------------Remove this
      result = data; // <------------------------Set the value of result
      keepGoing(); // <--------------------------Execute a callback
    });
    /* ... */
  })();

  console.log(result); // <----------------------Empty array, data not received yet

  function keepGoing() {
    console.log(result); // <--------------------Should be available now
  }

});