为什么 ajax 自动完成中的项目未定义?

发布于 2025-01-10 22:38:39 字数 2236 浏览 0 评论 0原文

我不明白 .net core 中的自动完成出了什么问题

 <p class="par-style">
        <input type="text" name="SearchString" placeholder="search..." class="col-sm-5 search-style" id="searchInput"/>
        <input type="submit" value="Search" class="search-button"/>
        <input type="submit" value="Clear" class="search-button" onclick="clearData();"/>
        <script>function clearData(){ document.getElementById("searchInput") = '';}
        $(document).ready(function () {    
        $("#searchInput").autocomplete({    
            source: function (request, response) {    
                $.ajax({    
                    url: "/Jewlery/AutoComplete",    
                    type: "POST",    
                    dataType: "json",    
                    data: { Prefix: request.term },    
                    success: function (data) {
                            response($.map(data, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                    }
            });
        });   
        </script>
    </p>

然后,我有控制器

        [HttpPost]
        public JsonResult AutoComplete(string prefix)
        {
            return Json( _jewleryService.AutoComplete(prefix));
        }

这个函数返回一个类型的对象

public class Jewlery
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string ImageUrl { get; set; }
        public string ImageThumbnailUrl { get; set; }
        public bool IsOnSale { get; set; }
        public bool IsInStock { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
    }

我也尝试返回一个对象 label:item.Name, value:item.Id,但它仍然不起作用。知道为什么吗?

I don't understand what goes wrong in autocomplete in .net core

 <p class="par-style">
        <input type="text" name="SearchString" placeholder="search..." class="col-sm-5 search-style" id="searchInput"/>
        <input type="submit" value="Search" class="search-button"/>
        <input type="submit" value="Clear" class="search-button" onclick="clearData();"/>
        <script>function clearData(){ document.getElementById("searchInput") = '';}
        $(document).ready(function () {    
        $("#searchInput").autocomplete({    
            source: function (request, response) {    
                $.ajax({    
                    url: "/Jewlery/AutoComplete",    
                    type: "POST",    
                    dataType: "json",    
                    data: { Prefix: request.term },    
                    success: function (data) {
                            response($.map(data, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                    }
            });
        });   
        </script>
    </p>

Then, I have the controller

        [HttpPost]
        public JsonResult AutoComplete(string prefix)
        {
            return Json( _jewleryService.AutoComplete(prefix));
        }

This function returns an object of type

public class Jewlery
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string ImageUrl { get; set; }
        public string ImageThumbnailUrl { get; set; }
        public bool IsOnSale { get; set; }
        public bool IsInStock { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
    }

I have also tried to return an object label:item.Name, value:item.Id, but it still does not work. Any idea why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏大泽ㄣ 2025-01-17 22:38:39

代码没有任何问题。问题是我试图访问 item.Name 而不是 item.name

success: function (data){
                            response($.map(data, function (item) {
                                return {
                            label: item.name,
                            value: item.name + ""
                                }}))
                        },

There was nothing wrong with the code. The problem was I was trying to access item.Name instead of item.name

success: function (data){
                            response($.map(data, function (item) {
                                return {
                            label: item.name,
                            value: item.name + ""
                                }}))
                        },
思念满溢 2025-01-17 22:38:39

根据您的代码,您正在传递一个对象,但根据 官方文档, autoComplete返回的数据类型是lable和Value的格式,所以会报错。如果成功,您可以将格式更改为自动完成支持的格式,如下所示。

success: function (data) {
                            response($.map(data, function (item) {
                                return {
                            label: item.Name,
                            value: item.Name + ""
                        } 

下面是一个工作demo,大家可以参考一下。

customer.cs:

public class customer
    {
      public string ContactName { get; set; }
        public int CustomerID { get; set; }
    } 

HomeController.cs:

public class HomeController : Controller
    {
        private readonly AutoCompleteInMVCJsonContext _context;

        public HomeController(AutoCompleteInMVCJsonContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
    public JsonResult AutoComplete(string prefix)
        {
            var customers = (from customer in _context.Customers
                             where customer.ContactName.StartsWith(prefix)
                             select customer).ToList();

            return Json(customers);
    }

索引视图:

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
    <link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
          rel="Stylesheet" type="text/css"/>
    <script type="text/javascript">
$(document).ready(function () {
            $("#txtCustomer").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Home/AutoComplete/',
                        dataType: "json",    
                        data: { "prefix": request.term },
                        type: "POST",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                            label: item.contactName,
                            value: item.contactName + ""
                        } 
                        
                      
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                }
             
            });
        });
    </script>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" id="txtCustomer" name="CustomerName"/>
      
   
        <input type="submit" id="btnSubmit" value="Submit"/>
      
    }
</body>
</html>

结果:
输入图像此处描述

According to your code, you are passing an object, but according to the official documentation, the data type returned by autoComplete is the format of lable and Value, so you will report an error. You can change the format to the format supported by autoComplete like below in your success.

success: function (data) {
                            response($.map(data, function (item) {
                                return {
                            label: item.Name,
                            value: item.Name + ""
                        } 

A work demo as below ,you can refer to it.

customer.cs:

public class customer
    {
      public string ContactName { get; set; }
        public int CustomerID { get; set; }
    } 

HomeController.cs:

public class HomeController : Controller
    {
        private readonly AutoCompleteInMVCJsonContext _context;

        public HomeController(AutoCompleteInMVCJsonContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
    public JsonResult AutoComplete(string prefix)
        {
            var customers = (from customer in _context.Customers
                             where customer.ContactName.StartsWith(prefix)
                             select customer).ToList();

            return Json(customers);
    }

Index view:

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
    <link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
          rel="Stylesheet" type="text/css"/>
    <script type="text/javascript">
$(document).ready(function () {
            $("#txtCustomer").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Home/AutoComplete/',
                        dataType: "json",    
                        data: { "prefix": request.term },
                        type: "POST",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                            label: item.contactName,
                            value: item.contactName + ""
                        } 
                        
                      
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                }
             
            });
        });
    </script>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" id="txtCustomer" name="CustomerName"/>
      
   
        <input type="submit" id="btnSubmit" value="Submit"/>
      
    }
</body>
</html>

result:
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文