在api请求上填充文本框

时间:2017-05-29 19:55:49

标签: javascript jquery

我在输入有效的邮政编码时尝试填充文本框(在keyup事件中使用正则表达式检查5位数)。我怎么能做到这一点?到目前为止,这是我的代码,我被卡住了:

<!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);
            });
        }

});

});

1 个答案:

答案 0 :(得分:0)

您要在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>