jQuery UI Autocomplete JSON给出错误:Uncaught TypeError:无法使用’in’运算符来搜索’62’

我在使用自动填充function在我的页面上工作时遇到了很多麻烦。 当我在搜索输入中输入2个字符(“OW”)时,我得到预加载器图像(见下文),但它永远不会消失,我从未得到自动完成弹出窗口。 查看Chrome中的控制台显示:

Uncaught TypeError: Cannot use 'in' operator to search for '62' in [{"value":103,"label":"FLOWER"},{"value":105,"label":"YELLOW"}] 

以下是要返回的实际字符串(通过在成功块中添加警报(数据)来确认):

 [{"kwrdID":103,"kwrdKeyWord":"FLOWER"},{"kwrdID":105,"kwrdKeyWord":"YELLOW"}] 

这是自动完成的主要代码

 $("#searchInput").autocomplete({ source: function (request, response) { $.ajax({ url: '@Url.Action("GetKeywords", "Home")', dataType: "json", data: { SearchTerm: request.term }, success: function (data) { response($.map(data.keywords, function (item) { return { label: item.kwrdKeyWord, value: item.kwrdID } })); } }); }, minLength: 2 }); 

最后,这里是预加载器(以防它是相关的)。

 $(document).ajaxStart(function () { var position = $('#divParent').position(); position.left += (($('#divParent').width() / 2) - ($('#preloader').width() / 2)); position.top += (($('#divParent').height() / 2) - ($('#preloader').height() / 2)); $('#preloader').css(position).show(); $('#preloader').show(); }).ajaxStop(function () { $('#preloader').hide(); }); 

谁能帮忙解释一下这里发生了什么?

这是一条漫长的道路,但经过几个小时的实验,我想出了这段代码:

 $("#searchInput").autocomplete({ source: function (request, response) { $.ajax({ url: '@Url.Action("GetKeywords", "Home")', dataType: "json", data: { SearchTerm: request.term }, success: function (data) { var parsed = JSON.parse(data); var newArray = new Array(parsed.length); var i = 0; parsed.forEach(function (entry) { var newObject = { label: entry.kwrdKeyWord }; newArray[i] = newObject; i++; }); response(newArray); }, error: function (message) { response([]); } }); }, minLength: 2 }); 

这似乎工作正常。 事实是我的关键字是独一无二的,所以无论如何我都可以没有身份证。

一点点有用的帮助:

如果你正在使用json,可能是因为“json对象”没有被解析,或者你已经用其他东西覆盖了变量(就像我最近做的那样愚蠢)。

对于第一个问题,请确保您的服务器知道“application / json”MIME类型,否则使用header(对于PHP)

我的意思是,在PHP中,首先使用它:

 header("Content-type: application/json"); 

如何将该函数用于source属性

 source:function(request,response) { var url = "your url"; var postdata = "your data"; // normally you might use request.term to get the current user input $.ajax({url:url,data:postdata,success:function(responsedata){ response($.parseJSON(responsedata)) }}); } 

响应函数接受JSON对象数组

而不是在这一行用JSON.parse(data)编写替换data.keywordsresponse($.map(data.keywords, function (item) {

BR,Hazem