gpt4 book ai didi

javascript - jquery中解析JSON数据的问题

转载 作者:行者123 更新时间:2023-11-28 07:49:14 25 4
gpt4 key购买 nike

我正在使用 jquery 自动完成功能使用邮政编码检索结果集。这是我尝试使用的代码...但它显示空行集

<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);
?>

提前致谢。

最佳答案

data.Addresses 是一个字符串数组。 IE。 item 是一个字符串。字符串没有 Addresses 属性。你的代码应该是

return {
label: item,
value: item
};

关于javascript - jquery中解析JSON数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com