简体   繁体   中英

JSON autocomplete, doesn't show results

I am trying to implement JSON for the first time, for an autocomplete input type.

@{
    ViewBag.Title = "Index";
}

<script type="text/javascript">
function searchFailed(){
$("#searchresults").html("Sorry, there was a problem with the search.");
}
    $("input[data-autocomplete-source]").each(function () {
        var target = $(this);
        target.autocomplete({ source: target.attr("data-autocomplete-source") });
    });
</script>

<h2>Index</h2>

@using (Ajax.BeginForm("QuickSearch", "Search", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnFailure = "searchFailed", LoadingElementId = "ajax-loader", UpdateTargetId = "searchresults", }))
{
<input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Search")" />

}

But it is complaining that data-autocomplete-source is not a valid attribute. It goes into the QuickSearch but I don't see a autocomplete result.

 target.data("autocomplete-source");

use the data attribute. jQuery. data


Replace:

$("input[data-autocomplete-source]").each(function () {
    var target = $(this);
    target.autocomplete({ source: target.attr("data-autocomplete-source") });
});

with:

$(function () {
    $("input[data-autocomplete-source]").each(function () {
        var target = $(this);
        target.autocomplete({ source: target.data("autocomplete-source") });
    });
});

You using $(function () {}) to wait until the page is "ready" and the element exists.


Change:

<input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Search")" />

to:

<input class="my-autocomplete" type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Search")" />

And change:

$("input[data-autocomplete-source]").each

to:

$("input.my-autocomplete").each

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