ラベル html5 の投稿を表示しています。 すべての投稿を表示
ラベル html5 の投稿を表示しています。 すべての投稿を表示

2018年10月7日日曜日

ASP.NET Core Web API - GET と POST

ASP.NET Core Web API で GET メソッドと POST メソッドの実装方法を調べてみました。


ValuesController.cs (一部抜粋)
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody] string id)
    {
    }
}

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input type="button" value="click" onclick="get()" />
    <input type="button" value="post" onclick="post()" />
    <script>
        function get(){
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        console.log("GET: 通信成功");
                    } else {
                        console.log("GET: 通信失敗");
                    }
                }
            };
            httpRequest.onload = function () {
                console.log("GET: 通信完了");
            };
            httpRequest.open("GET", "api/values", true);
            httpRequest.send(null);
        }

        function post() {
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        console.log("POST: 通信成功");
                    } else {
                        console.log("POST: 通信失敗");
                    }
                }
            };
            httpRequest.onload = function () {
                console.log("POST: 通信完了");
            };
            
            httpRequest.open("POST", "api/values", true);
            httpRequest.setRequestHeader('Content-Type', 'application/json');
            httpRequest.send(JSON.stringify("id=abc"));
        }
    </script>
</body>
</html>

POST を行うときには、setRequestHeader で Content-Type に application/json を指定する必要があります。ここが分からなくてしばらく調べました。

2018年9月22日土曜日

Flexbox を利用して要素を中央と右端に表示

Flexbox を利用して、要素を中央と右端に表示してみます。
parent クラスで display: flex としているので、justify-content に center とすることで、子要素(メインアイテム)を中央表示にしています。

item クラスで position: absolute としているので、子要素(メニュー)は 常に右端にくっついています。また、parent クラスで position: relative としているので、子要素(メニュー)は親要素の中で絶対位置の計算が行われます。

イメージ



CSS

<style>
    .parent {
        position: relative;
        display: flex;
        justify-content: center;

        border: black solid 1px;
        padding: 20;
    }

    .item {
        display: flex;

        margin: 3px;
        padding: 15px;
        border: black solid 1px;
    }

    .menu {
        position: absolute;
        right: 0;

        margin: 3px;
        padding: 15px;
        border: black solid 1px;
    }
</style>

HTML

<div class="parent">
    <div class="item">メインアイテム</div>
    <div class="item">メインアイテム</div>
    <div class="menu">メニュー</div>
</div>

2018年8月27日月曜日

入門:セマンティックマークアップで役に立ったリンク集

HTML5の文書構造「セマンティックマークアップ」まとめ
https://bsj-k.com/html5-semantic-markup/

→ 端的な説明で、セマンティックタグの説明をしてくれています。概要理解にとてもいいと思いました。


実践!すぐに導入できるセマンティックなマークアップ、4つのパターン
https://thinkit.co.jp/story/2012/04/25/3536

→ article は「自己完結型のコンテンツを配置する」という説明を見かけますが、いまいちピンと来ていませんでした。こちらの記事では、RSS フィードの例でわかりやすく説明してくれています。


HTML5.1を使ってSEOに強いセマンティックコーディングをする方法
https://fastcoding.jp/blog/all/html5toseo/

→ 「3. HTML5タグの正しいセクショニングを設定する」では、図解で分かりやすくタグの構成を解説してくれています。

2018年2月4日日曜日

Angular5 TODO リスト作成

Angular5 で簡易な TODO リストを作成する実装例を紹介します。

環境準備

node.js 及び npm のインストール

Angular によるアプリケーション開発を行うにあたり、これら機能を利用しますので、それぞれインストールします。インストール後、バージョンを確認します。

バージョン確認
node -v
npm -v

Angular インストール

次のコマンドで Angular CLI をインストールします。
npm install @angular/cli -g


Angular バージョ確認
ng -v


Angular CLI プロジェクトの作成、及びアプリケーションの起動

次のコマンドで Angular CLI プロジェクトを作成します。
ng new todoApp

作成したアプリケーションフォルダに移動
cd todoApp

アプリケーション起動
ng serve -o

→ ブラウザが起動してアプリケーションを表示


ここまでで開発の準備になります。ここから Angular CLI プロジェクトに実装を加えていきます。

機能実装

機能の実装は 1 ~ 15 のステップになります。

タスク数の表示

1.変数 taskText, taskCount を宣言する。

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  //1
  taskText:string;
  taskCount: number;
}


2.インターポレーションでテンプレートに taskCount を表示する。

app.component.html
<div style="text-align:center">
  <h1>
      タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>
</div>


3.FormsModule をインポートする。

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//3

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//3
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
}


タスクの追加機能

コンポーネントが初期化されるタイミングで発生するライフサイクルイベントをハンドルし、コンポーネントで利用する変数の初期化を行います。

4. OnInit をインポートする。
5. AppComponent に OnInit を実装する。
6. 変数 tasks を宣言する。
7. ngOnInit イベント内で taskText を空文字で、taskCount の値を tasks の要素数で初期化する。
8. addTask メソッドを追加する。

app.component.ts
import { Component, OnInit/*4*/ } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit/*5*/ {
  title = 'app';

  //1
  taskCount: number;
  tasks = [];//6
  
  ngOnInit(){
    //7
    this.taskText = "";
    this.taskCount = this.tasks.length;
  }

  //8
  addTask(taskNameValue: string){
    this.tasks.push(taskNameValue);
    this.taskCount = this.tasks.length;
  }
}

続いてテンプレート(HTML)側にも、データのバインドなどを実装していきます。


9. input(text) を実装し、taskName という名前をつける。
10. input(text) の value に ngModel を利用して taskText の値を双方向バインドする。
11. input(button) に click イベントを実装する。

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

ここまでで、input(button) をクリックすると、コンポーネント側で tasks 配列の要素が追加され、テンプレート側でバインドしている taskCount の値も増えていくことを確認することができます。

タスクのリスト表示

続けて、追加したタスクをリスト形式で表示するための実装を加えていきます。


12. tasks 配列の各要素をリスト表示する。

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

<ul>
  <!-- 12 -->
  <li *ngFor="let task of tasks">
    {{ task }}
  </li>
</ul>


13. タスクリストの位置調整

app.component.css
ul {
    position: relative;
    left: 40%;
}

ここまでで、ボタンクリックでタスクが追加していくようになります。

タスクの削除

タスクの追加ができたら、タスクの削除もできるようにします。タスクの削除は、タスク(li 要素)をクリックした時に行います。

14. input(button) に click イベントを登録する。

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

<ul>
  <!-- 12 -->
  <li *ngFor="let task of tasks; let idx = index;" (click)="removeTask(idx)"><!-- 14 -->
    {{ task }}
  </li>
</ul>

コンポーネント側で、タスクを削除するための removeTask イベントハンドラを実装します。

15. app.component.ts
//15
removeTask(idx:number){
  this.tasks.splice(idx, 1);
}

以上で、簡単ではありますが、Angular を利用した TO DO リストの作成ができました。


全ソースコード

各ファイルのソースコードは次のようになっています。

app.component.ts
import { Component, OnInit/*4*/ } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit/*5*/ {
  title = 'app';

  //1
  taskText:string;
  taskCount: number;

  tasks = [];//6
  
  ngOnInit(){
    //7
    this.taskText = "";
    this.taskCount = this.tasks.length;
  }

  //8
  addTask(taskNameValue: string){
    this.tasks.push(taskNameValue);
    this.taskCount = this.tasks.length;
    this.taskText = "";
  }
  //15
  removeTask(idx:number){
    this.tasks.splice(idx, 1);
  }
}

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

<ul>
  <!-- 12 -->
  <li *ngFor="let task of tasks; let idx = index;" (click)="removeTask(idx)"><!-- 14 -->
    {{ task }}
  </li>
</ul>

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//3

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//3
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.css
ul {
    position: relative;
    left: 40%;
}
以上になります。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2014年9月23日火曜日

localStorage への JSON データ保存と復元

cookie 以外でブラウザ側にデータを保存することの出来る localStorage があります。
ここでは簡単に localStorage へ JSON データを保存し、復元する例を紹介します。
JSON データは文字列データではないため、JSON.stringify() メソッドでシリアライズし、
JSON.parse() メソッドでデシリアライズしています。

// JSON データ
var friend = { ID : 1, Name : "Kai" };

// localStorage に JSON データを保存
// JSON.stringify を用いて JSON をシリアライズ(文字列化)
localStorage.setItem('kai', JSON.stringify(friend));

// 確認:変数 friend は JSON データ
console.log("json data : " + friend);

// 確認:localStorage には文字列として保存されている
console.log("localStorage data : " + localStorage.getItem("kai"));

// JSON.parse を用いてシリアライズされている JSON をデシリアライズ
var friendRetreived = JSON.parse(localStorage.getItem("kai"));

// JSON データが復元されている
console.log("deserialized data : " + friendRetreived);

2014年6月1日日曜日

html5 meter タグを使ってゲージを表示

html5 で導入された meter タグを使って数値、割合を表示してみましょう。

<meter value="70" low="30" max="100" high="90" optimum="70">値:70/100</meter>
値:70/100

<meter value="20" low="30" max="100" high="90" optimum="70">値:20/100</meter>
値:20/100

【属性】
value : 値
low : 下限値
high : 上限値
optimum : 最適値

value 属性の値が low 属性の値より小さいとゲージがオレンジ色になります。

2014年5月31日土曜日

html5 の機能がブラウザでサポートされているかを確認

window オブジェクトの配下にある html5 の機能名(プロパティ名)を判定することで確認することができます。

if (window.Worker) {
    // サポートしている場合
}
else {
    // サポートしていない場合
}

Detection Techniques
http://diveintohtml5.info/detect.html

2014年5月23日金曜日

for 属性によるラベルとコントロールの関連付け

html5 ではラベルの for 属性を利用してコントロールとの関連付けを行うことができます。関連付けを行ったラベルをクリックすると、コントロールにフォーカスしたり、選択することができるようになります。

    ラベルの"Text1"をクリックするとテキストボックスにフォーカス
    <label for="Text1">Text1</label>
    <input id="Text1" type="text" />

    テキストのRadio~をクリックするとラジオボタンにチェック
    <input id="Radio1" type="radio" name="group1" /><label for="Radio1">Radio1</label>
    <input id="Radio2" type="radio" name="group1" /><label for="Radio2">Radio2</label>
    <input id="Radio3" type="radio" name="group1" /><label for="Radio3">Radio3</label>

ラベルの"Text1"をクリックするとテキストボックスにフォーカス





テキスト部分(Radio~)をクリックするとラジオボタンにチェック



2014年5月12日月曜日

HTML5 Geolocation API で現在地取得

HTML5 の Geolocation API を利用して現在地を取得するサンプルです。

    <head>
        <script type="text/javascript">
            function getLocation() {

                var location = document.getElementById("currentLocation");

                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        location.innerHTML = 
                            "緯度: " + position.coords.latitude + " - " +
                            "緯度: " + position.coords.longitude;
                    });
                }
            }
        </script>
    </head>
    <body>
        <input type="button" onclick="getLocation()" value="Click"></input>
        <br/>
        <label id="currentLocation"></label>
    </body>

関連リンク:
HTML5 Geolocation
http://www.w3schools.com/html/html5_geolocation.asp