我正在尝试让 jQuery Mobile 自动完成功能正常工作,但它只能在外部数据上成功。当我尝试使用自己的 JSON 数据时,它失败了。
使用下面 js 中的注释行,它适用于外部数据,但不适用于我自己的数据。
js:
$( document ).on( "pageinit", "#mainPage", function() {
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
type : 'GET',
//url: "http://gd.geobytes.com/AutoCompleteCity",
url: "data/specs_search.php",
dataType: "jsonp",
data: {
q: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
specs_search.php JSON 输出:
["Rota, AN, Spain","Rotan, TX, United States","Rothbury, MI, United States","Rothesay, NB, Canada","Rothsay, MN, United States","Rothschild, WI, United States","Rothville, MO, United States","Rothwell, QL, Australia","Rotonda West, FL, United States","Rotorua, BP, New Zealand","Rottenburg, BW, Germany","Rotterdam Junction, NY, United States","Rotterdam, ZH, Netherlands","Barcarrota, EX, Spain","Brothers, OR, United States","Crothersville, IN, United States","Croton Falls, NY, United States","Croton on Hudson, NY, United States","Croton, OH, United States","Crotone, CA, Italy"]
HTML:
<p>After you enter <strong>at least three characters</strong> the autocomplete function will show all possible matches.</p>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a specification..." data-filter-theme="b"></ul>