这是我第一次在stack overflow上发帖,因为我已经寻找了一个多星期的解决方案,似乎找不到答案。
开始吧,我想使用OneMap搜索API来搜索特定的新加坡地区,我从https://www.geeksforgeeks.org/autocomplete-search-using-jquery-and-wikipedia-opensearch-api/获得了参考代码并做了一些更改。当使用维基百科开放搜索API时,它工作得非常好。
有谁能帮我提供一些建议,以便在输入"小印度"等新加坡地区时能够搜索和显示自动补全建议?如有任何帮助,我将不胜感激,谢谢。
请参考以下现有代码:
<!DOCTYPE html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<link rel="stylesheet" href="
https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<script src="
https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
</script>
<style>
body {
width: 100%;
background: #e9e9e9;
margin: 0 auto;
padding: 0;
color: #7faf7f;
font-family: Arial, sans-serif;
font-size: 12px;
}
#searchID input {
width: 350px;
height: 20px;
margin: 0;
padding: 15px;
background: #fff;
border: 1px solid black;
color: #727272;
float: left;
font: 12px "Lucida Sans Unicode", sans-serif;
transition: background 0.4s ease-in-out 0s;
}
#searchID button {
width: 45px;
height: 45px;
text-indent: -9999em;
background: #4eac10;
transition: background 0.3s ease-in-out 0s;
border: 1px solid #fff;
}
#containerID {
width: 50%;
margin: 0 auto;
}
h2 {
color: green;
text-align: left;
}
</style>
</head>
<body>
<div id="containerID">
<form method="get" id="searchID">
<input type="text" class="searchClass"
id="searchInputID" value="" />
<button type="submit">Search</button>
</form>
</div>
</div>
<script type="text/javascript">
$(".searchClass").autocomplete({
source: function (request, response) {
console.log(request.term);
var suggestURL = "https://developers.onemap.sg/commonapi/search?returnGeom=N&getAddrDetails=N&searchVal=%QUERY";
suggestURL = suggestURL.replace('%QUERY', request.term);
// JSON Request
$.ajax({
method: 'GET',
jsonCallback: 'jsonCallback',
url: suggestURL,
// "http://en.wikipedia.org/w/api.php",
dataType: "application/json",
data: {
// action: "opensearch",
// Output format
format: "application/json",
search: request.term,
namespace: 0,
// Maximum number of result
// to be shown
limit: 8,
},
})
.success(function(data) {
response(data[4]);
});
},
});
</script>
</body>
</html>
我找到了我的问题的答案,通过使用map方法并调用键的名称('SEARCHVAL')来获取其值,并将其作为一个名为searchValues的变量传递给响应。请看下面的脚本:
<script type="text/javascript">
$(".searchClass").autocomplete({
source: function (request, response) {
var oneMapURL = "https://developers.onemap.sg/commonapi/search?returnGeom=N&getAddrDetails=N&searchVal=%QUERY";
URL = oneMapURL.replace('%QUERY', request.term);
// JSON Request
$.ajax({
url: URL,
dataType: "json",
data: {
// Output format
format: "json",
search: request.term,
namespace: 0,
},
})
.success(function(data) {
var sgAreas = data.results;
var searchValues = sgAreas.map(function(sgArea) {
return sgArea['SEARCHVAL'];
});
response(searchValues);
});
},
});
</script>