简体   繁体   English

在不重新加载页面的情况下填充下拉框

[英]Populate Dropdown Box without Reloading Page

I have started learning PHP/HTML this week as my company needs a little tool that will return a list of suburbs based on a postcode. 我本周开始学习PHP / HTML,因为我的公司需要一个小工具,该工具将根据邮政编码返回郊区列表。 My knowledge is very limited but I have been able to get it to work exactly how I want. 我的知识非常有限,但是我已经能够使其完全按照我的要求工作。 Except with the onchange/onblur, it reloads the whole page. 除了onchange / onblur外,它会重新加载整个页面。 I can't seem to work out or find a way to only reload the dropdown box. 我似乎无法解决或找到只重新加载下拉框的方法。 From searching the internet it seems Jquery or Javascript will be the only way to do this. 通过搜索互联网,看来Jquery或Javascript将是实现此目的的唯一方法。 But I can't find an example/tutorial close enough to what my needs are. 但是我找不到足够接近我需要的示例/教程。

Here is the code. 这是代码。 Basically, you fill out the text input, off click places the postcode number into an API, which then returns all the corresponding suburbs in JSON format. 基本上,您填写文本输入,然后单击将邮政编码编入API,然后以JSON格式返回所有相应的郊区。 A dropdown box is then populate by the JSON data. 然后,由JSON数据填充一个下拉框。

Your help is greatly appreciated! 非常感谢您的帮助!

<?php
//Turn data from user entry screen into variables
$pcode = $_GET["pcode"];
//Load API key and API URL
include 'api.php';

//Initializing curl
$ch = curl_init($url);
//Setting curl options
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//Getting results
$api_result = curl_exec($ch);
//Close Curl
curl_close($ch); 

//Place API call results into $data variable
$suburb_data = json_decode($api_result, TRUE);

//Display JSON Data - Comment out in production
//var_export($suburb_data);

//Turn suburb list array in a variable
$suburb_list = ($suburb_data['result']);

//Count the amount  of results
//$suburb_count = count($suburb_list);
?>

<form method="get">
  <table width="308" border="0">
    <tr>
      <td width="95">Postcode:</td>
      <td width="98"><label>
        <input name="pcode" type="text" id="pcode" onblur="this.form.submit()" style="width: 40px;"onchange='this.form.submit()' value="<?php echo htmlspecialchars($_GET['pcode']); ?>" />
      </label></td>
      <td width="88"></td>
    </tr>
    <tr>
      <td>Suburb:</td>
      <td><label>
<?php
echo'<select name="city">';
//Loop through the array "results" and find all values for "Town"
foreach ($suburb_list as $towns) {
    echo '<option value="'.$towns['Town'].'">'.$towns['Town'].'</option>';;
}
echo '</select>';

?>
      </label></td>
      <td></td>
    </tr>
    <tr>
      <td><label>
        <input type="submit" name="button" id="button" value="Submit" />
      </label></td>
      <td></td>
      <td></td>
    </tr>
  </table>

</form>

使用ajax ,它将允许您从服务器发送和检索数据,而无需重新加载页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM