从邮政编码中查找地址并编辑输入表单,而无需重新加载页面

时间:2019-04-27 08:16:02

标签: php jquery html ajax

我正在尝试向正在构建的注册页面添加一些功能。

该功能是从邮政编码中查找地址,并将该数据添加到输入表单中。

我找到了一种方法来执行此操作,但是我执行此操作的方式涉及一些问题。目前,我正在使用带有提交按钮的表单,然后使用if(isset($ _ post),这意味着一旦按下我不希望的提交按钮,页面将被重新加载。

我的想法是,我需要使用一些jquery或ajex来完成此任务,而无需重新加载表单,但是老实说,我不确定从哪里开始。

我编写了一个函数,该函数以数组形式返回我需要的数据

postcode_api_test.php

<?php
function lookuppostcode($postcode)
{
    $postcode = str_replace(" ", "", $postcode);
    $key = 'MY API KEY';
    $request = 'https://api.getAddress.io/v2/uk/' . $postcode . '?api-key=' . $key;
    $response = file_get_contents($request);
    $jsonresponse = json_decode($response, true);
    $returnData = array();

    $returnData['lat'] = $jsonresponse['Latitude'];
    $returnData['lon'] = $jsonresponse['Longitude'];
    $returnData['totalAddresses'] = count($jsonresponse['Addresses']);

    $addressArray = explode(',', $jsonresponse['Addresses'][0]);
    $returnData['locality'] = $addressArray[4];
    $returnData['city'] = $addressArray[5];
    $returnData['county'] = $addressArray[6];

    $returnData['addresses'] = array();

    foreach ($jsonresponse['Addresses'] as $address) {
        $addressArray = explode(',', $address);
        $fullAddress = '';

        foreach ($addressArray as $item) {
            if ($item != ' ') {
                $fullAddress .= $item . ",";
            }
        }
        $fullAddress = trim($fullAddress, ",");
        $returnData['addresses'][] = array(
            'line1' => $addressArray[0],
            'line2' => $addressArray[1],
            'line3' => $addressArray[2],
            'line4' => $addressArray[3],
            'locality' => $addressArray[4],
            'city' => $addressArray[5],
            'county' => $addressArray[6],
            'fullAddress' => $fullAddress,
        );
    }
    return $returnData;
}
?>

postcode.php:

<?php
include 'postcode_api_test.php';
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "ajex_test.js"> </script>

<form   method="post">
<form method = "post">
<div class="form-group">
    <label class="control-label">Entity Type</label>
    <label class="control-label">Title</label>
    <input type="text" name="postcode" id="postcode" class="form-control" value = "">
    <button class="btn btn-success"  onclick = "postcodelookup()" name = "postcodebtn" id="postcodebtn">  </button>


<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

</form>
</form>

我想知道是否有人对如何启动它有任何指示?

ajax_test.js

function postcodelookup($postcode){
    $("#postcodebtn").click(function(){
    $.ajax({
        type: "GET",
        url: "postcodecall.php",
        data:{"postcode":$("#postcode").val},
        success: function(data){

            $("#div1").html(data);

        }
    });
});

};

postcodecall.php

<?php
include 'postcode_api_test.php';

if(isset($_GET["postcode"])){

$postcode = $_GET["postcode"];
lookuppostcode($postcode);
echo $data;
}
?>

1 个答案:

答案 0 :(得分:0)

对于遇到此问题的任何人,这是我的工作代码,如有任何评论,请告诉我。

我创建的页面使用我创建的函数以json格式返回数据。然后,我创建了对该页面的ajax调用,使我无需重新加载poscode_api主页面即可访问此信息。

如果有请分享的话,可能会有一种更流畅的方法。这对我有用,似乎很简单。

以下代码:

_测试页

postcode.php

<?php
include 'postcode_api_test.php';
?>
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "ajex_test.js"> </script>


<div class="form-group">
    <label class="control-label">Postcode</label>

    <input type="text" name="postcode" id="postcode" class="form-control" value = "">
    <button  onclick = "postcodelookup()"  name = "postcodebtn" id="postcodebtn">  </button>
    <select name = "postcode_lookup" id = "postcode_lookup" style = "display = hidden;">
    <option value = "Please Select"> </option>
    </select>


    <div>  <input type="text" name="addressline1" id="addressline1" class="form-control" value = ""> <label> Addressline1</div>
    <div>  <input type="text" name="addressline2" id="addressline2" class="form-control" value = ""> <label> Addressline2</div>
    <div>  <input type="text" name="addressline3" id="addressline3" class="form-control" value = ""> <label> Addressline3</div>
    <div>  <input type="text" name="addressline4" id="addressline4" class="form-control" value = ""> <label> Addressline4</div>
    <div>  <input type="text" name="town" id="town" class="form-control" value = ""> <label> town</div>
    <div>  <input type="text" name="county" id="county" class="form-control" value = ""> <label> county</div>


</html>

postcodecall.php

<?php
include 'postcode_api_test.php';

if (isset($_GET["postcode"]) && $_GET["postcode"] != "") {

    $postcode = $_GET["postcode"];
    $data = lookuppostcode($postcode);
    $fulladdress = array();
    foreach ($data['addresses'] as $address) {
        $fulladdress[] = $address['fullAddress'];
    }

    $jsondata = json_encode($fulladdress);
    echo $jsondata;

}

ajax_test.js

function postcodelookup($postcode)
{    
        $.ajax(
        {
            type: "GET",
            url: "postcodecall.php",
            data:{postcode: $('#postcode').val()},
            dataType: 'json',

            beforeSend :function()
            {       
                $("#postcode_lookup option:gt(0)").remove(); 
                $('#postcode_lookup').find("option:eq(0)").html("Please wait..");
            },
            success: function(data)
            {
                $('#postcode_lookup').show();
                $('#postcode_lookup').find("option:eq(0)").html("Please select your Address");
                alert('Please Select Address from the list - If your address is not here please enter manually. Thanks');
                postcode_dropdown = '';
                $(data).each(function(addressline,fulladdress)
                {      
                fulladdresstrim = fulladdress.replace(/ ,/g, '')


                postcode_dropdown += '<option value = "' + fulladdress+'"> '+ fulladdresstrim +' </option>';                   
                });             
                $('#postcode_lookup').append(postcode_dropdown);        
            },
            error: function(jqxhr, status, exception) {
                alert('Exception:', exception);
            }

        });

}



    $(document).ready(function(){
        $('#postcode_lookup').hide();
        $('#postcode_lookup').on('change',function(){           
            var fulladdress = $(this).val();
            var addressline = fulladdress.split(",");
                $('#addressline1').val(addressline[0]);
                $('#addressline2').val(addressline[1]);
                $('#addressline3').val(addressline[2]);
                $('#town').val(addressline[5]);
                $('#county').val(addressline[6]);

        });
    });

postcode_api_test.php

<?php


function lookuppostcode($postcode)
{
    $postcode = str_replace(" ", "", $postcode);
    $key = 'MY API CODE';
    $request = 'https://api.getAddress.io/v2/uk/' . $postcode . '?api-key=' . $key;
    $response = file_get_contents($request);
    $jsonresponse = json_decode($response, true);
    $returnData = array();
    $returnData['lat'] = $jsonresponse['Latitude'];
    $returnData['lon'] = $jsonresponse['Longitude'];
    $returnData['totalAddresses'] = count($jsonresponse['Addresses']);
    $addressArray = explode(',', $jsonresponse['Addresses'][0]);
    $returnData['locality'] = $addressArray[4];
    $returnData['city'] = $addressArray[5];
    $returnData['county'] = $addressArray[6];

    $returnData['addresses'] = array();

    foreach ($jsonresponse['Addresses'] as $address) {
        $addressArray = explode(',', $address);
        $fullAddress = '';

        foreach ($addressArray as $item) {

                $fullAddress .= $item . ",";

        }
        $fullAddress = trim($fullAddress, ",");
        $returnData['addresses'][] = array(
            'line1' => $addressArray[0],
            'line2' => $addressArray[1],
            'line3' => $addressArray[2],
            'line4' => $addressArray[3],
            'locality' => $addressArray[4],
            'city' => $addressArray[5],
            'county' => $addressArray[6],
            'fullAddress' => $fullAddress,
        );
    }
    return $returnData;
}
?>