0
我知道這裏有很多關於JsonP的問題 - 我幾乎經歷了所有的答案和 - 無法爲我的生活找到爲什麼我沒有得到正確的結果。我花了幾個小時,幾小時來回,嘗試不同的內容,等等。總之,到它的疙瘩:jQuery JSONP「undefined」回覆
我的腳本(在同一頁上我的形式)
$(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));
我從窗口小部件中得到彈出窗口,但沒有內容。當我選擇彈出的空列表框,它追加「undefinedundefined」,顯然來自:
log(ui.item ?
"Selected: " + ui.item.label + ui.item.value :
"Nothing selected, input was " + this.value);
我已簽了JSON發送和在Firefox螢火/ Web開發插件接受,我也得到
0: Object
data: Object
value: "1"
label: "Cyprus"