我知道在这里有很多关于JsonP的问题 - 我几乎已经完成了所有的答案而且 - 无法 - 为我的生活找到了为什么我没有得到正确的结果。我花了好几个小时,几个小时来回走动,尝试不同的尝试,ETC.无论如何,直到它的一块:
我的脚本(与我的表格在同一页面上)
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$("#name").autocomplete({
source: function( request , response ) {
$.ajax({
url: "search.php",
jsonp: "callback",
data: {
term: request.term
},
dataType: "jsonp",
type: "GET",
success: function (data, status) {
if (status=="success") {
$("#log").html(response);
}
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label + ui.item.value :
"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" );
}
});
});
我的表格(与脚本相同的页面)
<form method="post" action="">
Name : <input type="text" id="name" name="name" />
</form>
<div class="ui-widget" style="margin-top:2em; font-family:Arial" id="log">
<p>Result</p>
</div>
我的search.php
if (empty($_GET['term'])) exit ;
require 'php/config/sql.inc.php';
$link = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_NAME) or die(sqlerror(mysqli_error($link), __LINE__, __FILE__));
$req = "SELECT supplier_id, supplier_name FROM supplier WHERE supplier_name LIKE '".mysqli_real_escape_string($link, $_GET['term'])."%'";
$query = mysqli_query($link, $req);
while($row = mysqli_fetch_array($query))
{
$results[] = array('data' =>
array(
'value' => $row['supplier_id'],
'label' => $row['supplier_name']
)
);
}
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Nov 2014 05:00:00 GMT');
header('Content-type: application/json');
echo ((isset($_GET['callback'])) ? $_GET['callback'] . '(' . json_encode($results) . ')' : json_encode($results));
我从小部件中获取弹出窗口,但没有内容。当我选择弹出的空列表框时,它会附加&#34; undefinedundefined&#34;,显然来自:
log( ui.item ?
"Selected: " + ui.item.label + ui.item.value :
"Nothing selected, input was " + this.value );
我已经在firefox中的firebug / web dev插件中检查了JSON发送和接收,我得到了
0: Object
data: Object
value: "1"
label: "Cyprus"