在api请求上填充文本框
问题描述:
我试图在我输入有效的邮政编码(5位数字与关键事件正则表达式检查)时填入文本框。我会如何做到这一点?这是到目前为止我的代码,我已经得到了坚持:在api请求上填充文本框
<!DOCTYPE html>
<html>
<head>
<title>Get ZipCode Data</title>
</head>
<body>
<div>
<label>Zip Code:</label>
<input type="text" id="zipcode" value=""><br/ >
<label>City:</label>
<input type="text" id="city" value=""><br/ >
<label>State:</label>
<input type="text" id="state" value=""><br/ >
<div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JQuery的:
$("document").ready(function(){
$("#zipcode").keyup(function(e){
var zipcode = $("#zipcode").val();
var googleAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=";
if (zipcode.length == 5)
{
$.getJSON(googleAPI + zipcode + function(data){
$("#city").val(data.results[0].address_components[1].long_name);
$("#state").val(data.results[0].address_components[3].long_name);
});
}
});
});
答
你加入的JSON请求不必要+看googleAPI + zipcode + function(data){
,而是+你应该使用,
看到下面的代码:
$("#zipcode").keyup(function(e){
var zipcode = $("#zipcode").val();
var googleAPI = "https://maps.googleapis.com/maps/api/geocode/json?address=";
if (zipcode.length == 5)
{
$.getJSON(googleAPI + zipcode ,function(data){
$("#city").val(data.results[0].address_components[1].long_name);
$("#state").val(data.results[0].address_components[3].long_name);
});
}
});
<!DOCTYPE html>
<html>
<head>
<title>Get ZipCode Data</title>
</head>
<body>
<div>
<label>Zip Code:</label>
<input type="text" id="zipcode" value=""><br/ >
<label>City:</label>
<input type="text" id="city" value=""><br/ >
<label>State:</label>
<input type="text" id="state" value=""><br/ >
<div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>
我完全没注意到。感谢您指出,Omi。 – Maxlong007