简体   繁体   中英

jQuery autocomplete not working with JSON

I am trying to implement the jQuery autocomplete. I feel like everything is set up just fine, however It's not working.

SearchSkies method

public JsonResult SearchSkies(string query)
{
     SkiDao skiDao = new SkiDao();
     IList<Ski> skies = skiDao.SearchSkies(query);    
     List<string> brands = (from Ski s in skies select s.Brand).ToList();
     return Json(brands, JsonRequestBehavior.AllowGet);
}

The script in View

<script type="text/javascript">
  $( function() {
    $( "#searchBox" ).autocomplete({
      source: function( request, response ) {
        $.ajax( {
          url: '@Url.Action("SearchSkies","Skies")',
          dataType: "json",
          data: {
            query: request.term
          },
          success: function (data) {
              response(data);
          }
        } );
      },
      minLength: 2,
    });
  });
</script>

You are not mentioning type of request(GET/POST) in ajax call.

$(document).ready(function () {  
       $("#searchBox").autocomplete({  
           source: function(request,response) {  
               $.ajax({  
                   url: "/Skies/SearchSkies",  
                   type: "POST",    <<----
                   dataType: "json",  
                   data: { query: request.term },  
                   success: function (data) {  
                       response($.map(data, function (item) {  
                           return { label: item.Name, value: item.Name };  
                       }))      
                   }  
               })  
           },  
           messages: {  
               noResults: "", results: ""  
           }  
       });  
   })

And the controller

public class SkiesController : Controller  
{  
        // GET: Home  
        [HttpGet]  
        public ActionResult Index()  
        {  
            return View();  
        }  
        [HttpPost]  
        public JsonResult SearchSkies(string query)  
        {                
        SkiDao skiDao = new SkiDao();
        IList<Ski> skies = skiDao.SearchSkies(query);

        List<string> brands = (from Ski s in skies select s.Brand).ToList();
        return Json(brands, JsonRequestBehavior.AllowGet);
        }  
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM