2014-03-29 66 views
1

不知道爲什麼我試圖用ajax源實現自動完成時仍然會出現此錯誤。jQuery autocomplete ajax TypeError

"Uncaught TypeError: Cannot read property 'length' of undefined" 

這是我的快遞路線。

exports.findAllIrds = function(req, res) { 
    var name = req.query["value"]; 
    db.collection('employees', function(err, collection) { 
     if (name) { 
      collection.find({ 
       "value": new RegExp(name, "i") 
      }, { 
       value: 1, 
       data: 1, 
       _id: 0 
      }).toArray(function(err, items) { 
       res.jsonp(items); 
       //console.log(req.query); 
       //console.log(items); 
      }); 
     } else { 
      collection.find().toArray(function(err, items) { 
       res.jsonp(items); 
       console.log(req.query); 
      }); 
     } 
    }); 
}; 

如果我瀏覽到/ receiversjson我讓我所有的JSON作爲預期,當我瀏覽/ receiversjson?值= 293589324我得到

[{"value": "2935893244","data": "D33HL3RH311911"}]預期。

但是,當我嘗試使用下面的代碼jquery自動完成時,我得到錯誤。

$('.item-name textarea').autocomplete({ 
    serviceUrl: '/receiversjson', 
    paramName: 'value', 
    autoSelectFirst: true, 
    onSelect: function(suggestion) { 
     alert('You selected: ' + suggestion.value + ', ' + suggestion.data); 
    } 
}); 



Uncaught TypeError: Cannot read property 'length' of undefined 

在Chrome開發者工具的網絡標籤之我見「receiversjson?值= 293589324」,當我點擊它,它打開一個網頁與我的JSON。

[{ 
    "value": "2935893244", 
    "data": "D33HL3RH311911" 
}] 

我在想什麼或做錯了什麼?

enter image description here

+0

你的HTML看起來像什麼?只是猜測,但它不能找到你的textarea?你可能有一個糟糕的jquesry選擇器? – caspian

+0

我不再在我的電腦前發佈HTML。但我相信選擇器是正確的,因爲在輸入textarea時發生錯誤。 – fpena06

+0

哦,我想確定什麼時候發生錯誤......我不確定你可以使用自動完成與textarea,你可以嘗試將它附加到類型文本或搜索的輸入? – caspian

回答

3

我的問題是JSON的迴應並沒有包括 「建議:」 我的產量爲這個

[ 
    { 
    "value": "1999458647", 
    "data": "A10GA8CW330293" 
    } 
] 

JQuery的自動完成功能一直在尋找這一點。

{ 
    "suggestions": [ 
    { 
     "value": "1999458647", 
     "data": "A10GA8CW330293" 
    } 
    ] 
} 

我目前正在處理它。

exports.findAllIrds = function(req, res) { 
    var name = req.query["value"]; 
    db.collection('employees', function(err, collection) { 
     if (name) { 
      collection.find({"value": new RegExp(name, "i")},{value:1,data:1,_id:0}).toArray(function(err, items) { 
       var myobj = {}; 
       var suggestions = 'suggestions'; 
       myobj[suggestions] = items; 
       res.jsonp(myobj); 
      }); 
     } else { 
      collection.find().toArray(function(err, items) { 
       res.jsonp(items); 
       console.log(req.query); 
      }); 
     } 
    }); 
};