Jquery Autocomplete JSON string parsing error

﹥>﹥吖頭↗ 提交于 2019-12-01 12:44:16

问题


I want to use Jquery autocomplete in my web application but encounter issues. I am developing my application in ASP.NET and JQuery.

Here's the part of the Autocopmlete 'succes' function:

success: function (data) {
     response($.map(data.d, function (item) {
         return {
              label:  item.key,
             value: item.value
            }
       }));
     },

My webservice returns the following JSON:

"[{"key":"Bread","value":"3"}]"

When I run it I get Javascript error:

Uncaught TypeError: Cannot use 'in' operator to search for '42' in [{"key":"bread","value":"3"}] 

It looks like that the returned JSON is not in the right format for the $.map function from what I can tell. Also the result might return several items, not just one as seen above.

Can anyone help me solve this issue. I am using JSON as the dataType and GET as the type in the Ajax call.


回答1:


I simply suggest you instead of using any other method you can use :

success: function (data, status, xhr) {
    var jsonArray = JSON.parse(data);  // Normal way
}

Other way

success: function (data, status, xhr) {
    var jsonArray = $.parseJSON(data); // using jQuery
}

In this way it will be converted to a simple JavaScript object which you can easily manipulate on your UI/DOM.




回答2:


You're right -- your JSON is an array which contains a single object. You're expecting just that object.

Try modifying your code like so:

success: function (data) {
  data = data[0]; 


来源:https://stackoverflow.com/questions/14363444/jquery-autocomplete-json-string-parsing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!