15
19

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 5 years have passed since last update.

jQueryを利用せずにAjaxを利用するサンプル

Posted at

風の噂によれば、世の中には「DOM操作を多用するが、jQueryは禁止」という開発現場があるそうです(血涙)

まずはjsonをPOSTする例。

// jsonの準備
var json = {};
json.name = "nekoTheShadow";
json.job = "SystemsEngneer";

// XMLHttpRequestオブジェクトの生成
var xhr = new XMLHttpRequest();

// methodとurlを指定
xhr.open("POST", "/post/json");

// イベントリスナを設定
xhr.addEventListener("progress", function(){}); // 通信中
xhr.addEventListener("load", function(){}); // 通信成功
xhr.addEventListener("error", function(){}); // 通信失敗
xhr.addEventListener("abort", function(){}); // 通信をキャンセル

// Content-Typeを設定
xhr.setRequestHeader("Content-Type", "application/json");

// 送信
xhr.send(JSON.stringify(json));

次は普通(?)にPOSTする例:


// 送信するデータの準備
var data = "name=nekoTheShadow&job=SystemsEngneer";

// XMLHttpRequestオブジェクトの生成
var xhr = new XMLHttpRequest();

// methodとurlを指定
xhr.open("POST", "/post/json");

// イベントリスナを設定
xhr.addEventListener("progress", function(){}); // 通信中
xhr.addEventListener("load", function(){}); // 通信成功
xhr.addEventListener("error", function(){}); // 通信失敗
xhr.addEventListener("abort", function(){}); // 通信をキャンセル

// Content-Typeを設定
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

// 送信
xhr.send(data);

ご査収ください(´・ω・`)

15
19
2

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
15
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?