JavaScript ES6 応用(更新中) - user000422/0 GitHub Wiki
// 一旦動いたものを張り付けただけ Laravel + blade + Javascript
const btnLogin = document.getElementById('login');
btnLogin.addEventListener('click', function() {
const email = document.getElementById('email');
const password = document.getElementById('password');
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch("http://localhost/api", {
method: "POST",
body: JSON.stringify({
email: email.value,
password: password.value,
}),
headers: {
"Content-type": "application/json",
'X-CSRF-TOKEN': csrfToken
},
})
.then((response) => response.json())
.then((json) => console.log(json));
}, false);
// GET
const btn = document.getElementById('sample');
btn .addEventListener('click', function() {
fetch("/api/search", {
method: "GET",
headers: {
'Authorization': 'Bearer ' + accessTokenValue,
},
})
.then(response => response.json())
.then(data => {
});
}, false);
子要素を全て削除
while(parent.lastChild) {
parent.removeChild(parent.lastChild);
}
JSON(JavaScript Object Notation)
文字コードはUTF-8
固定
XML
と比較しデータ量が少ない(軽い)
文字列はダブルクォーテーション
{
"id": 1,
"name": "Taro"
}
JSON配列
{
"sample": [
{"id":1},
{"name":"Taro"}
]
}
AjaxでJSON取得処理 ※IE10以降
非同期処理は処理順序に保証がないので、returnは頭を抱える
promise
とfetch
はIEに対応していない
responseTypeプロパティ
のjson
はIEに対応していないのでresponseTypeプロパティ
は使わないことに…
const url_json = './json/sample.json';
function getJson(url_json) {
const XHR = new XMLHttpRequest();
XHR.open('get', url_json);
XHR.send();
XHR.addEventListener('readystatechange', function() {
if(XHR.readyState === 4 && XHR.status == 200) {
const result = JSON.parse(XHR.response);
}, false);
}
confirm('ダイアログに表示させたい文字列'); // confirm メソッド
var ○○○ = confirm('xxx'); // 返り値用変数宣言 "OK"が押されると"true" , "キャンセル"が押されると"false"
Cookieをブラウザコンソールで編集
document.cookie = 'sample_cookie=sample_value';
HTMLの<script>
タグ内にHTMLコメントがある理由
昔JavaScriptを理解できないブラウザが存在しておりそのなごり
<script>
<!--
-->
</script>
開発中でのクロスドメイン制約回避
chromeのショートカット作成
-> ショートカットを右クリック
-> プロパティ
下記をリンク先に入力(自分の環境に合わせたパス)
chrome.exe --allow-file-access-from-files --allow-file-access --allow-cross-origin-auth-prompt --disable-web-security --user-data-dir="C:\Users\xxxxx\AppData\Local\Google\Chrome\User Data"
このショートカットは開発中でのクロスドメイン制約回避用として使えるようになる
Ajax(Asynchronous JavaScript XML) … ブラウザとWebサーバ間で非同期通信を行う技術
XMLHttpRequest
というAPIを使い実現する
処理結果は Json
もしくは xml
で応答
HTMLタグの「デフォルト動作」をキャンセルさせる
aタグ … クリックされたら href で指定されているページへ遷移
formタグ … action属性 で指定されているURLへ入力内容を送信しページ遷移
document.getElementById('○○○').onclick = function(event){
event.preventDefault();
// 処理内容
};
Window.open … ウィンドウをポップアップ表示
fullscreen
オプションは、最大化ではなくフルスクリーン表示