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

时间:2015-08-26 18:26:24

标签: javascript typeahead.js

我正在研究typeahead.js脚本,我没有得到正确的答案,我尝试过很多东西但没有工作。 这个网址正在从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 = [" Gold's Gym Hiranandani"," Golds Gym Marol Naka"," Gold's Gym Chembur" ," Gold's Gym Bandra West"," Gold's Gym Kandivali East"," Gold's Gym Lower Parel",& #34; Gold's Gym Vashi"," Gold's Gym Kandiwali west"," Gold's Gym Mulund West"," Gold's Gym - Mona Fitness Center Private Limited"," Gold's Gym Borivali west"," Jignya Johri @ Gold" && 34; #34; Gold's Gym Thane West"," Golds Gym Khar west"," Gold's Gym Grant Road(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');
});

1 个答案:

答案 0 :(得分:0)

设置结果的函数是异步的。它不能立即返回数据,所以当它等待它时,它会继续执行它下面的代码。为防止这种情况,请使用回调:

$(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
  }

});