这是我的jquery ajax调用的成功部分:
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
response($.map(data.d, function (item) {
return {
label: item.ItemName,
val: item.ItemId
}
}))
},
这是data
我从服务器获取此成功块:
[{"ItemId":1095,"ItemName":"Double Axe"},{"ItemId":1096,"ItemName":"Helm"},{"ItemId":1097,"ItemName":"Armor"},{"ItemId":1098,"ItemName":"Gloves"},{"ItemId":1099,"ItemName":"Boots"}]
我得到的错误是:
Uncaught TypeError: Cannot read property 'length' of undefined
问题是response($.map(data.d, function (item) {
永远不会被执行
我应该怎么做才能使这项工作?
答案 0 :(得分:0)
您当前正在将json 字符串传递给需要数组或对象的$.map()
方法。使用JSON.parse()
解析您获得的响应。
以下似乎工作正常:
var data = [{
"ItemId": 1095,
"ItemName": "Double Axe"
}, {
"ItemId": 1096,
"ItemName": "Helm"
}, {
"ItemId": 1097,
"ItemName": "Armor"
}, {
"ItemId": 1098,
"ItemName": "Gloves"
}, {
"ItemId": 1099,
"ItemName": "Boots"
}];
$("#tags").autocomplete({
"source": function(request, response) {
response($.map(data, function(item) {
return {
label: item.ItemName,
val: item.ItemId
}
}));
}
});
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags" />
</div>