我正在开发一个自动填写地址的项目。我首先选择一个国家。一旦我选择了一个国家,我希望只能从该国家中选择县。我希望能够从所选国家/地区中选择ID并将其发送到网址中,以便用户只能选择该国家/地区的县。如果我将此$ .getJSON(" includes / county.php?countryId =" + countryId,req,function(data))更改为此$ .getJSON(" includes / county.php?countryId =" + 372,req,函数(数据)它的工作原理,但是如何将国家的id输入到url中的countryId变量?
NO
html表单:
//Country
$(document).ready(function () {
$("#country").autocomplete({
//Defines the callback to format the results
source: function (req, add) {
$.getJSON("includes/country.php", req, function (data) {
//Creates an array for results
var suggestions = [];
//Processes the response
$.each(data, function (i, val) {
suggestions.push(val);
});
//Pass thr array to callback
add(suggestions);
});
},
//Defines the select handler
select: function (e, ui) {
$("#country").val(ui.item.value);
}
});
});
//Selecting the county
$(document).ready(function () {
$("#county").autocomplete({
//Defines the callback to format the results
source: function (req, add) {
$.getJSON("includes/county.php?countryId=" + countryId, req, function (data) {
//Creates an array for results
var suggestions = [];
//Processes the response
$.each(data, function (i, val) {
suggestions.push(val);
});
//Pass thr array to callback
add(suggestions);
});
},
//Defines the select handler
select: function (e, ui) {
$("#county").val(ui.item.value);
}
});
});
Country.php文件:
<div class="field">
<label id="countryLabel">Country: </label>
<div id="friends" class="ui-helper-clearfix">
<input type="text" name="country" id="country">
</div>
</div>
<div class="field">
<label id="countyLabel">County: </label>
<div id="friends" class="ui-helper-clearfix">
<input type="text" name="county" id="county">
</div>
</div>
County.php文件:
<?php
require_once("database.php");
$country = $_GET["term"];
if ($country != null) {
$queryCountry = "SELECT * FROM countries WHERE country LIKE :country";
$statement = $db->prepare($queryCountry);
$statement->bindValue(":country", $country."%", PDO::PARAM_STR);
try {
$statement->execute();
}
catch(PharException $e) {
echo $e->getMessage();
exit();
}
$results = $statement->fetchAll();
$statement->closeCursor();
$countries = array();
foreach ($results as $result){
$countries[$result['id']] = $result['country'];
}
$response = json_encode($countries);
echo $response;
}