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.
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.
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