2012-06-17 128 views
2

我想爲自動完成輸入類型首次實現JSON。JSON自動完成,不顯示結果

@{ 
    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")" /> 

} 

但它是抱怨數據自動完成源不是一個有效的屬性。它進入快速搜索,但我沒有看到自動完成的結果。

回答

0
target.data("autocomplete-source"); 

使用數據屬性。 jQuery的。 data


替換:

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

有:

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

您使用$(function() {})等到頁面是 「準備」 和元素存在。


變化:

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

到:

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

而變化:

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

到:

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

我必須在哪裏添加target.data? – user1408786

+0

這是在呼喚我的行動。但是我沒有在建議列表中看到該行動的結果? – user1408786