[Html 5 / jQuery] datalist 元素的 Ajax版 with ASP.net 後端語言

Html5 datalist Ajax

在恆逸的上課筆記,覺得是個好用的範例,所以隨便記、快速記,無法詳細說明XD

ASP.net WebForm 後端↓

<%@ Page Language="C#" %>
<%@ Import Namespace="Newtonsoft.Json" %>
<script runat="server">
    // /sample_datalist.aspx?q=h
    void Page_Load(object sender, EventArgs e)
    {
        string key = Request.QueryString["q"];
        if (key == null) return;

        Response.ContentType = "application/json";

        string[] data ={"HOME","HTML","HTML4","HTML5","ASP.NET", "ASP.NET Web Form",
                  "ASP.NET MVC"};

        string s = JsonConvert.SerializeObject(data.Where(k => k.Contains(key.ToUpper())));
        Response.Write(s);

    }

</script>

HTML的寫法↓

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form id="form1" action="https://www.google.com/search" method="GET" target="_blank">
        <input id="text1" type="text" name="q" list="list1" 
            autocomplete="off" >
        <input type="submit" value="send">
    </form>
    <datalist id="list1">       
    </datalist>
    <!--引用jQuery函式庫-->
    <script src="Scripts/jquery-3.4.1.js"></script>
    <script>
        $(function () {

            $("#text1").on("input", function () {
                //console.log(this.value, $(this).val());
                $("#list1").empty();

                $.ajax({
                    url: "sample_datalist.aspx",
                    data:$("#form1").serialize()
                }).done(function (data) {
                    console.log(data);
                    data.forEach(function (item) {
                        $("#list1").append($("<option>").text(item));
                    });
                });
            });
        });
    </script>
</body>
</html>