There are a whole bunch of tutorials out there explaining how to do this, eg here and here.
Looks real easy huh? Yet I've still somehow managed to waste half a day on it without getting anything working.
Eg: the following works absolutely fine
public ActionResult FindStuff(string q)
{
return Content("test");
}
$('#MyTextBox').autocomplete("MyController/FindStuff", {
parse: function(data) {
alert('parsing');
}
});
If I change it to the following, absolutely nothing happens.
public JsonResult FindStuff(string q)
{
return Json(new { name = "test" });
}
$('#MyTextBox').autocomplete("MyController/FindStuff", {
dataType: 'json', // I've also tried with this line commented out
parse: function(data) {
alert('parsing');
}
});
So it looks like the parse
call is never being hit, i.e. I'm assuming the data load is blowing up somehow or thinks ther开发者_如何学编程e is no data. Any ideas? Thanks.
p.s. it's the Jorn Zaefferer plugin here.
Make sure that you are returning an array and that you allow GET requests (in case your are using ASP.NET MVC 2.0):
public ActionResult FindStuff(string q)
{
return Json(new[] { new { name = "test" } }, JsonRequestBehavior.AllowGet);
}
And then follow the examples:
$('#MyTextBox').autocomplete("MyController/FindStuff", {
dataType: 'json',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i].name };
}
return rows;
},
formatItem: function (row, i, n) {
return row.name;
}
});
Works nicely.
Remark: FireBug helps diagnosing problems very quickly as it shows you exactly what AJAX requests are being sent and why they succeed or fail.
精彩评论