Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active March 4, 2017 13:22
Show Gist options
  • Save sekky0905/2f559566bc55812a0603c3ee656d819e to your computer and use it in GitHub Desktop.
Save sekky0905/2f559566bc55812a0603c3ee656d819e to your computer and use it in GitHub Desktop.
Go言語とTypeScript(JavaScript)でライブラリなしでAjaxなコードをXMLHttpRequestオブジェクトを使って書いてみた ref: http://qiita.com/Sekky0905/items/07affe9e68744eba6c89
apprppt
|_source
| |_index.js
| |_index.ts
| |_package.json
| |_tsconfig.json
|_view
| |_index.html
|_main.go
{
"name": "ajax",
"version": "1.0.0",
"description": "ajax",
"main": "./index.js",
"scripts": {
"start": "",
"build": "tsc index.ts"
},
"author": "",
"license": "MIT",
"devDependencies": {
"typescript": "^2.1.6"
},
"dependencies": {},
"directories": {},
"repository": {
"type": "git",
"url": "github.など"
},
"author": "",
"license": "MIT",
"bugs": {
"url": "github.など"
},
"homepage": "github.など"
}
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "es5",
"declaration": true,
"sourceMap": true,
"lib": [
"dom",
"es5"
],
"noImplicitAny": true,
"strictNullChecks": false,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitUseStrict": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"traceResolution": false,
"listFiles": false,
"stripInternal": true,
"skipDefaultLibCheck": true,
"skipLibCheck": false,
"pretty": false,
"noEmitOnError": true
},
"include": [
"./**/*.ts"
],
"types": [
],
"exclude": [
"node_modules",
"code/definition-file/usage/",
"code/definition-file/augmentGlobal/",
"code/definition-file/issue9831/",
"code/**/*-invalid.ts",
"code/**/*-invalid.d.ts",
"code/**/invalid.ts",
"code/**/invalid.d.ts",
"code/**/*-ignore.ts",
"code/**/*-ignore.d.ts",
"code/**/ignore.ts",
"code/**/ignore.d.ts"
]
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<p id="click-here"> click here</p>
<script type="text/javascript" src="../source/index.js"></script>
</body>
</html>
名前 : Go
型 : Static
const id = 'click-here';
// idで指定して、elemntを取得
const e = document.getElementById(id);
// イベントリスナー登録
// クリックされたら、コールバック関数発動
e.addEventListener('click', () => {
// 生のjavaScriptでAjaxを行うためには、XMLHttpRequestを使用する
// XMLHttpRequestインスタンスの生成
const httpRequest = new XMLHttpRequest();
// openメソッド : リクエストを初期化する
// 第1引数で、GETかPOSTのリクエストメソッドを指定
// 第2引数で、"リクエスト先のURL"
// 第3引数で、同期か非同期かの選択(非同期の場合は、true)
httpRequest.open("GET", "/json", true)
// readyStateプロパティ : XMLHttpRequestオブジェクト(HTTPリクエスト)のサーバとの通信の状態
// この値がサーバとの通信状態によって変化する
// readyStateプロパティの値が変化するたびにonreadystatechangeイベントが発生する
// このonreadystatechangeイベントが発生したら、readyStateプロパティをチェックすれば、現在の通信状態を知ることができる
console.log(httpRequest.readyState);
// XMLHttpRequestオブジェクト(HTTPリクエスト)のonreadystatechangeイベントが発生したら、=で与えた関数が発動する
httpRequest.onreadystatechange = () => {
// 通信が完了したならば
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
// jsonをtextデータとして受け取る
const jsonText = httpRequest.responseText
// textデータとして受け取ったjsonをパース
const json = JSON.parse(jsonText);
// 通信が完了(受信)したら、行う処理を記載
e.innerHTML = `
<p>名前: ${json["Name"]}</p>
<p>型 : ${json["LangType"]}</p>
`
}
}
// sendメソッド : openで作成したHTTPリクエストをサーバへ送信する
// POSTの場合は、送信するデータを引数で与える
// GETの場合は、nullを引数で与える
httpRequest.send(null);
// 非同期のテスト
// 非同期で通信しているので、HTMLの<p>が変化するよりもこちらの方が先に呼び出される
window.alert('非同期');
})
package main
import (
"fmt"
"net/http"
"html/template"
"encoding/json"
)
func main() {
fmt.Println("The Server runs with http://localhost:8080/")
http.Handle("/source/", http.StripPrefix("/source/", http.FileServer(http.Dir("source/"))))
http.HandleFunc("/", Handler)
http.HandleFunc("/json", JsonHandler)
http.ListenAndServe(":8080", nil)
}
// 構造体
type Language struct {
Name string
LangType string
}
func Handler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("./view/index.html"))
tmpl.Execute(w, nil)
}
func JsonHandler(w http.ResponseWriter, r *http.Request) {
// 構造体をインスタンス化
l := Language{Name : "Go", LangType: "Static"}
// Header() : WriteHeaderによって送信されるheaderのmapを返す
// func (h Header) Set(key, value string)
// headerエンティティのkeyに対してvalueを関連付ける
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// WriteHeader(int) : ステータスコードと共にHTTPのレスポンスヘッダを送信する
// http.StatusOKは200が設定されている
w.WriteHeader(http.StatusOK)
// Encoderは、出力ストリームにJSONオブジェクトを書き込む
// NewEncoder(w io.Writer) : wに書き込みを行い、新しいEncoderを返す
// Encode() : 引数のJSONエンコーディングをWriterに書き込む
json.NewEncoder(w).Encode(l)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment