【JavaScript】ファイルの更新があれば、値を更新する

setTimeoutでループ処理ができる。
data.split(“\n”).lengthで、ファイルの行数を取得できる。

async function fetchData() {
  try {
    fetch('./data/names.txt')
    .then(response => response.text())
    .then(data => {
        console.log('テキストファイルの内容:');
        console.log(data.split("\n").length - 1);
        document.getElementById('target').textContent = data.split("\n").length - 1;
    })
    .catch(error => {
        console.error('エラー:', error);
    });
  } catch (error) {
    console.error('リクエストエラー:', error);
  }
  setTimeout(fetchData, 3000);
}
fetchData();

これだと、更新自体はできますが、データをpublicな場所には置きたくないですね…

【Rust】サーバ側からTera/JavaScriptにデータを渡すとき

JSに渡すときに、let value = {{ data }} と書くと宜しくない。let value = “{{ data }}” とダブルクオテーションで囲って渡してあげる必要がある。

サーバ側

    let tera = tera::Tera::new("templates/*").unwrap();

    let data = 100;

    let mut context = tera::Context::new();
    context.insert("title", "Index page");
    context.insert("data", &data);

    let output = tera.render("index.html", &context);
    return axum::response::Html(output.unwrap());

html/JS側

//
<input type="range" class="form-range" id="customRange1" min="0" max="{{data}}" v-model="amount">
//
<script>
    let value = "{{ data / 2 }}";
</script>

↓ これは動くには動くが駄目。

<script>
    let value = {{ data / 2 }};
</script>

【javascript】アップロードファイルのプレビュー

<form action="/post" method="post" enctype="multipart/from-data">
    <div>
        <input type="file" name="test" onchange="previewFile(this);">
    </div>
    <div>
        <input type="submit" value="送信する">
    </div>
</form>
<p>プレビュー</p>
<img id="preview" width="100px" height="100px">

<script>
function previewFile(file) {
    var fileData = new FileReader();
    fileData.onload = (function() {
        document.getElementById('preview').src = fileData.result;
    });
    fileData.readAsDataURL(file.files[0]);
}
</script>

次はaxumでデータのやり取りだな

【Rust】AxumでCSS, JSなどstaticファイルを使いたい時

tower-http = { version = “0.6.2”, features = [“fs”] }

staticフォルダにcssファイルを置きます。
static/styles.css

h1 {
    color:red;
}

template/test.html

<head>
    <title>title</title>
    <link rel="stylesheet" href="styles.css">
</head>
<h1>Hello world</h1>

main.rs

use tower_http::services::{ServeDir, ServeFile};
use axum::{
    routing::get,
    Router,
};

#[tokio::main]
async fn main() {

    let serve_dir = ServeDir::new("static").not_found_service(ServeFile::new("static"));

    let app = Router::new()
        .route("/", get(handle_index))
        .nest_service("/static", serve_dir.clone())
        .fallback_service(serve_dir);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handle_index()-> axum::response::Html<String> {
    let tera = tera::Tera::new("templates/*").unwrap();

    let mut context = tera::Context::new();
    context.insert("title", "Index page");

    let output = tera.render("test.html", &context);
    axum::response::Html(output.unwrap())
}

なるほど、これでCSSもjsも自由にコーディングできますね。

javascriptのsplitメソッド

splitは指定した文字列または正規表現によって文字列が分割され、結果が配列になって帰って来る

var str = "あ、い、う";
console.log(str.split("、"));

$ node main.js
[ ‘あ’, ‘い’, ‘う’ ]

正規表現

console.log(str.split(/[0-9]./));

区切り文字を残す場合

var str = "あ、い、う";
console.log(str.split(/(?<=、)/g));

()で囲まれていると残り、囲まれていないと削除

console.log(str.split(/(、)/));

$ node main.js
[ ‘あ’, ‘、’, ‘い’, ‘、’, ‘う’ ]

jsのrequireの使い方

分割した機能ごとのjsファイルのことをモジュールと呼ぶ
importを使うのがESM方式(ECMAScript Module)で、requireを使うのがCJS(CommonJS Modules)

### import文の書き方
モジュール側

export const helloWorld = function() {
    console.log('Hello World!');
}

読み込み側

import { helloWorld } from './module'

helloWorld();

### require
モジュール側
L module.exportsと書く

module.exports = function() {
    console.log('hello world!');
}

読み込み側
 L require文を使って先ほどのモジュールを読み込む

const helloWorldModule = require('./module.js');

helloWorldModule();

$ sudo apt install nodejs
$ node main.js
hello world!

読み込まれる方でmodule.export()とするのが鍵ですね。

JavaScriptでjsonを表示する

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
	<ul id="list">
<!-- ここに出力します -->
	</ul>
	<script>
		$(function(){
			json = "./list.json";
			target = $("#list");
			$.getJSON(json, function(data, status){
				for(var n in data){
					var text = '<li>';
					if (data[n].url){
						line = '<a href="'+data[n].url+'" target="_blank"><span>'+data[n].name+'</span></a>';
					} else {
						line = '<i><span>'+data[n].name+'</span></i>';
					}
					text = text+line+'</li>';
					$(target).append(text);
				}
			})
		})
	</script>
</body>
</html>

これは分かり易いですね。

チャット返答のJavaScript側の処理を考える

チャットの返答前に処理一覧を表示させたいので、Promiseで以下のように書ければ良い

	console.log("処理開始");

	new Promise((resolve, reject)=> {
		console.log("送信者のメッセージをDBへインサート処理");
		list();
		setTimeout(function(){
			resolve();
		}, 2000);
	}).then(function(value){
		console.log("API回答メッセージをDBへインサート処理");
		list();
	}).catch((data) => console.log(data)
	).finally(() => console.log("処理終了"));

	async function list(){
		console.log("DBからリストを表示");
	}

あとは(1)JavaScriptからPHP側にデータをどのように送るか、(2)DBからデータを取得するかを考える

JavaScript Promiseとは

Promiseは処理が問題なく完了すればresolve、反対に問題があればrejectを呼び出してメッセージを表示
コールバックとは、ある関数へ別の関数を渡すこと

sampleFunction1(function(data1){
	sampleFunction2(function(data2){
		// 処理
	})
})
	var sample = new Promise(function(resolve, reject){
		setTimeout(function(){
			resolve();
		}, 1000);
	});

	sample.then(function(value){
		console.log("Promise成功!");
	});

	console.log("先に出力");

Promiseの処理を連結させるものをchainという