SYNCERのロゴ
アイキャッチ画像

FormData.get() - データを1つ取得する

get()は、FormDataのメソッドです。ある名前のフォームのデータを1つ取得します。

概要

名前
get
所属
FormData
IDL
FormDataEntryValue? get(USVString name);

typedef (File or USVString) FormDataEntryValue;
仕様書
https://xhr.spec.whatwg.org/#dom-formdata-get

説明

引数(name)には、キー名を指定します。

キー名の値を返します。

デモ

FormData.get()のデモです。"name"のデータを取得します。

<!-- このコードは編集できます。 -->

<!DOCTYPE html>
<html>
<head>
<style>
body { word-break: break-all ; tab-size: 2 ; }
div#result { white-space: pre-wrap ; }
textarea#fuga { box-sizing: border-box ; width: 100% ; font-size: 16px ; }
</style>
</head>
<body>
<p><button id="append">追加</button></p>
<p><button id="reset">リセット</button></p>
<hr>
<div id="result"></div>
<hr>
<p><button id="send">ajax通信で送信</button></p>
<hr>
<textarea rows="15" id="fuga">ajax通信の結果</textarea>
<script>
var formData = new FormData() ;
var xhr = new XMLHttpRequest() ;
getFormDataInfo() ;

xhr.onloadend = function ( event ) {
	console.log( xhr ) ;
	document.getElementById( "fuga" ).value = xhr.response ;
}

document.getElementById( "append" ).onclick = function () {
	formData.append( "name", "あらゆ" ) ;
	getFormDataInfo() ;
}

document.getElementById( "reset" ).onclick = function () {
	formData = new FormData() ;
	getFormDataInfo() ;
}

document.getElementById( "send" ).onclick = function () {
	xhr.open( "POST", "https://syncer.ch/POST" ) ;
	xhr.send( formData ) ;
}

function getFormDataInfo () {
	document.getElementById( "result" ).textContent = "" ;

	console.log( formData ) ;
	appendText( formData + "\n" ) ;

	formData.forEach( function ( value, name ) {
		appendText( name + ": " + value + "\n" ) ;
	} ) ;

	appendText( "getAll(): " + "\n" + JSON.stringify( formData.getAll( "name" ) ) + "\n" ) ;
}

function appendText ( text ) {
	document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
50+ 39+××× 37+××
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年10月24日 (火)
コンテンツを公開しました。