0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ajaxのソースコード

Posted at

実務でJavaのシステムで実装したAjaxのソースコードを自分用にメモとしてまとめました。

まずはJavaScriptでイベントを作成し、通信する。

$('#button').click(function() {
	var req = new XMLHttpRequest();
	var url = 'コンテキスト以降のURL';
	req.open('GET',url);
	req.send();

	req.onreadystatechange = function() {
		if (req.readyState === 4 && req.status === 200) {
			let info = (req.responseText)?JSON.parse(req.responseText):null;
			if (info) {
				console.log(info);
			}
		}
	}
});

指定したURLのサーブレットを作ってJSONデータを返す。

// レスポンス用JSON文字列生成
String resData =
	"{\"mojiretsu1\":\"" + "mojiretsu1" +
	"\",\"mojiretsu2\":\"" + "mojiretsu2" +
	"\",\"mojiretsu3\":\"" + "mojiretsu3" +
	"\"}";

// レスポンス処理
response.setContentType("text/plain");
response.setCharacterEncoding("utf8");
PrintWriter out = response.getWriter();
out.println(resData);

文字列はtry,catch構文でデータベースに接続してデータベースから取ってきたり、サーブレットで生成したりする。

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?