忍者ブログ

からすまる日誌

(今日の最後のコード 郵便番号検索)

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

(今日の最後のコード 郵便番号検索)

--->test1.html
 
<!DOCTYPE html>
<html lang="ja">
 <head>
  <meta charset="utf-8">
  <title>API</title>
  <link rel="stylesheet" href="test1.css">
  <script src="../jquery-3.4.1.min.js"></script>
 </head>
 <body>
  <h3>住所検索</h3>
  <div>
   <p>
    <label>
     郵便番号 <input id="zipcode" type="text size="10" maxlength="8">
    </label>
    <button id="btn">検索</button>
   </p>
   <p>
    <label>
     都道府県 <input id="prefecture" type="text" size="10">
    </label>
   </p>
   <p>
    <label>
     市区町村 <input id="city" type="text" size="10">
    </label>
   </p>
   <p>
    <label>
     住所   <input id="address" type="text" size="10">
    </label>
   </p>
   <p>
    <input type="radio" name="r1" id="r1"><label for="r1">ラジオボタン1</label></input>
    <label><input type="radio" name="r1" id="r2">ラジオボタン2</input></label>
    <label><input type="radio" name="r1" id="r3">ラジオボタン3</input></label>
   </p>
  </div>
 
  <script src="test1.js"></script>
 </body>
</html>
 
 
--->test1.js
 
$(function(){
 console.log('foo');
 
 $('#btn').on('mouseout',function(){
  //非同期通信開始
  $.ajax({
   url: 'http://zipcloud.ibsnet.co.jp/api/search',
   dataType: 'jsonp',/*受信時のデータ形式。書式のこと*/
   type: 'get',/*送信時の通信タイプ getがdefaultなので書かないくてもgetになるが書きましょう*/
   data: {'zipcode':$('#zipcode').val()},/*引き渡すデータ。複数のデータを渡すかもしれないのでオブジェクトで渡す*/
  })
  .done(function(hoge){
  //通信成功
   //console.log(hoge);
   console.log(hoge.results);
   //console.log(hoge.results[0]);
   var d = hoge.results[0];/*いったん変数に格納*/
   //console.log(d.address1);/*東京都を取得*/
   
   $('#prefecture').val(d.address1);/*入力欄に書き出すのはval。idの#を忘れずに*/
   $('#city').val(d.address2);
   $('#address').val(d.address3);
  })
  .fail(function(hoge){
  //通信失敗
   console.log('通信失敗');
  });
 });
});
PR

コメント

ブログ内検索

カレンダー

03 2025/04 05
S M T W T F S
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30