我是Javascript的新手,所以请多多关照!
我有一个 Html 表单,我已成功编写脚本以从我的 SQL 数据库中查找商店,并在选定半径内的谷歌地图上将点定位到用户邮政编码。
有一个供用户输入邮政编码的自由文本字段和两个列表框,一个用于预设半径值,另一个用于预设商店类型。
如果选择商店类型 Type1
或 Type2
我的代码工作正常,但我希望用户能够选择 All
并返回 map 上的 Type1
和 Type2
。
对我来说显而易见的事情是在 searchUrl 变量(如下)中有一个 if 语句,说明如果选择了 All
然后使用没有 + '&BusinessType=' + businesstypechoice 的 url
部分放在最后,否则使用现有的 url。
无论我如何尝试编写 if 语句,我都无法使表单/ map 工作,它不会返回任何值。
如何正确编写 if 语句或者是否有更好的方法?
HTML
<input type="text" id="addressInput" placeholder="Enter Postcode" size="13"/>
<select id="radiusSelect">
<option value="10" >10 mi</option>
<option value="25" selected>25 mi</option>
<option value="50" >50 mi</option>
<option value="100">100 mi</option>
<option value="200">200 mi</option>
</select>
<select id="businesstypeSelect">
<option value="All" selected>All</option>
<option value="Type 1" >Type 1</option>
<option value="Type 2" >Type 2</option>
</select>
<input type="button" onClick="searchLocations()" value="Search"/>
Javascript(我认为与此处相关的函数部分)
var radius = document.getElementById('radiusSelect').value;
var businesstypechoice = document.getElementById('businesstypeSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?Latitude=' + center.lat() + '&Longitude=' + center.lng() + '&radius=' + radius + '&BusinessType=' + businesstypechoice;
downloadUrl(searchUrl, function(data) {
函数继续。如果您需要查看更多内容,请告诉我。
提前致谢!
编辑:
我对 if 语句的最新尝试:
var searchUrl;
if(businesstypechoice == 'All') {
searchurl = 'phpsqlsearch_genxml.php?Latitude=' + center.lat() + '&Longitude=' + center.lng() + '&radius=' + radius;} else
if(businesstypechoice != 'All') {
searchurl = 'phpsqlsearch_genxml.php?Latitude=' + center.lat() + '&Longitude=' + center.lng() + '&radius=' + radius + '&BusinessType=' + businesstypechoice;}
downloadUrl(searchUrl, function(data) {
phpsqlsearch_genxml.php 文件的第一部分。
// Get parameters from URL
$center_lat = $_GET["Latitude"];
$center_lng = $_GET["Longitude"];
$radius = $_GET["radius"];
$business_type = $_GET["BusinessType"];
我想我需要一个针对 $business_type 变量的 if 语句来告诉它在选择“All”时不要查找 BusinessType,因为“All”不存在于我的 SQL 数据库的 BusinessType 列中。
最佳答案
您能否在服务器上调试并查看通过查询字符串获取的数据?问题也可能与您的服务器端代码有关。
也就是说我是三元运算符的忠实粉丝。
var radius = document.getElementById('radiusSelect').value;
var businesstypechoice = document.getElementById('businesstypeSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?Latitude=' + center.lat() + '&Longitude=' + center.lng() + '&radius=' + radius;
searchUrl = (businesstypechoice === "All") ? searchUrl : searchUrl + '&BusinessType=' + businesstypechoice;
downloadUrl(searchUrl, function(data) {
这等同于说“如果 businesstypechoice
等于所有则返回 searchUrl
,否则返回 searchUrl
加上新的查询参数。
还要注意你的 Camel 外壳。 BusinessTypechoice
应该是 businessTypeChoice
关于使用 if 语句的 Javascript 变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051745/