我正在使用jQuery自動完成功能使用postcode檢索結果集。在這裏,我想使用的代碼...但它顯示空行集在jQuery中解析JSON數據的問題
<html lang="en">
<head>
<meta charset="utf-8">
<title>Auspost Postcode search</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
$(function() {
$("#postcode").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'json.php', //your server side script
dataType: 'json',
data: {
postcode: request.term
},
success: function (data) {
//if multiple results are returned
if(data.Addresses instanceof Array)
response ($.map(data.Addresses, function (item) {
return {
label: item.Addresses,
value: item.Addresses
}
}));
}
});
}
});
});
</script>
</head>
<body>
<form action="auspost.php" method="post">
<label for="postcode">Postcode:
<input name="postcode" id="postcode" type="text">
</label>
<input type="submit" value="submit" />
</form>
</body>
</html>
這是我公司通過API接收的JSON編碼的結果集(從json.php響應)。
{
"Latitude": -0.020223,
"Longitude": 51.504859,
"Addresses": [
"Abbey Offices Ltd, 1 Canada Square, LONDON",
"B B V A, 1 Canada Square, LONDON",
"B P R Interiors Ltd, 1 Canada Square, LONDON",
"Citihub Ltd, 1 Canada Square, LONDON",
"Coutts & Co, 1 Canada Square, LONDON",
]
}
這裏是我的json.php文件代碼:
<?php
$postcode = urlencode($_POST['postcode']);
$username = "api-key";
$password = "my-api-key"; // here i will include my api key
$remote_url = 'https://api.getAddress.io/uk/'.$postcode;
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Basic " . base64_encode("$username:$password")
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($remote_url, false, $context);
print_r($file);
?>
在此先感謝。
那麼,這不是有效的JSON(http://jsonlint.org/)。鑰匙必須是字符串。這就是爲什麼它不能被解析。請參閱https://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example。 – 2014-11-21 08:55:40
對不起抱歉@FelixKling ..thats我的錯誤我使用JSON解析器這是一個鉻擴展名..其中我複製了JSON代碼 – 2014-11-21 09:00:40