JS
$( "#ethnicbg" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: 'ethnic/',
type: 'POST',
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.title,
value: item.value
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
// log( ui.item ?
// "Selected: " + ui.item.label :
// "Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
PHP
header('Content-type: application/json');
$url = $this->url->get();
$arr = get_data(); // returns [{"title":"White","value":"White"}]
echo json_encode($arr);
它返回数据,问题出现在 success: function 的某个位置,就在
response($.map....
之前。我放了 console.log('TEST')
,似乎根本不会到那里,也不会弹出任何东西,我做错了什么?解决方案:
dataType: "jsonp"
应该是 dataType: "json"
。如果有人能解释一下 json 和 jsonp 的区别吗?在这种情况下,这将有助于我和其他可能遇到此类问题的人。