0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

入力フォームの郵便番号で入力補助

Posted at

お世話になります。
内容はタイトル通りなのですが、現在入力フォームの郵便番号の入力補助機能を作成しているのですが、jqueryの読み込みでエラーが出てつまずいてしまいました、すごく初歩的なことでお恥ずかしいのですがご教授いただければ幸いです。

全体的な流れを記載します

1.郵政省からダウンロードしたCSVをコンバートして必要な情報だけにする←ここの実装はできています
2.入力フォームで入力された郵便番号をAJAXでapi.phpに渡し候補をコールバック

※1前提として、グーグル・マップAPI、ライブラリ等は使用しないことを考えています

form.html
<!DOCTYPE html>
<html>
<head>
<title>郵便番号で住所入力補助</title>
<meta charset="utf-8">
<script src="../js/jquery-1.11.3.min.js"></script>
 
<script type="text/javascript">
$(document).ready(function(){
    $("#lookup").click(function(){
        var zip1 = $.trim($('#zip1').val());
        var zip2 = $.trim($('#zip2').val());
        var zipcode = zip1 + zip2;
 
        $.ajax({
            type: "post",
            url: "api.php",
            data: JSON.stringify(zipcode),
            crossDomain: false,
            dataType : "jsonp",
            scriptCharset: 'utf-8'
        }).done(function(data){
            if(data[0] == ""){
                alert('見つかりませんでした。');
            } else {
                $('#address').val(data[0] + data[1] + data[2]);
            }
        }).fail(function(XMLHttpRequest, textStatus, errorThrown){
            alert(errorThrown);
        });
     });
});
</script>
</head>
<body>
<form>
    <p>郵便番号:<input type="text" name="zip1" id="zip1" size="6">-<input type="text" name="zip2" id="zip2" size="6">
    <input type="button" id="lookup" value="郵便番号で検索"></p>
    <p>住所:<input size="50" type="text" name="address" id="address"></p>
</form>
</body>
</html>
api.php
<?php
$dir = __DIR__ . '/zipcode';
 
// Ajax以外からのアクセスを遮断
$request = (string)filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH');
if(strtolower($request) !== 'xmlhttprequest') exit;
 
$json = file_get_contents('php://input');
$data = json_decode($json, true);
file_put_contents('test.log', print_r($data, true));
$zipcode = !empty($data) ? $data : '';
$zipcode = mb_convert_kana($zipcode, 'a', 'utf-8');
$zipcode = preg_replace('/[\sー-]/', '', $zipcode);
 
$callback  = (string)filter_input(INPUT_GET, 'callback');
$callback  = htmlspecialchars(strip_tags($callback));
 
$param = array('', '', '');
 
$file = $dir . DIRECTORY_SEPARATOR . substr($zipcode, 0, 1) . '.csv';
if(file_exists($file)){
    $spl = new SplFileObject($file);
    while (!$spl->eof()) {
        $columns = $spl->fgetcsv();
        if(isset($columns[0]) && $columns[0] == $zipcode){
            $param = array($columns[1], $columns[2], $columns[3]);
            break;
        }
    }
}
 
header('Content-type: application/javascript; charset=utf-8');
printf("{$callback}(%s)", json_encode( $param ));
0
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?