LoginSignup
11
11

More than 5 years have passed since last update.

JSON の送受信を jQuery なしで行ってみる

Last updated at Posted at 2016-08-10

jQuery を使いたくない場合向けに...
WEB上のあちらこちらで紹介されている(しかしいまいちまとまっていない気が)、JavaScript (AJAX)や PHPASP.NET(MVC) による JSON の送受信コード例をまとめました。初歩的な内容でスミマセンが、随時修正や補足追加をしていきたいと思います。
以下、変数 data を JSON文字列でやりとりする例を示します。

JavaScript の XMLHttpRequest

IE7以前は XMLHttpRequest が使えず、"Microsoft.XMLHTTP"を利用していました。

送信

var xhr = new XMLHttpRequest();
var jsonText = JSON.stringify(data); // ここで、dataをJSON文字列に変換
xhr.open("POST", "http://sample/folder/");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonText);

受信

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
 if(this.readyState == 4) {
     if (this.status == 200){
       data = this.response;
     }
 }
};
xhr.open("GET", "http://sample/folder2/", true); // POSTでも利用可能
xhr.responseType = 'json'; // これを指定しないと、responseにJSON文字列が返る
xhr.send();

+XMLHttpRequest.readyState プロパティ
+XMLHttpRequest.status プロパティ
+XMLHttpRequest.onreadystatechange イベント

PHP

送信

$json_string = json_encode($data); // ここで、$dataをJSON文字列に変換
header("Content-Type: application/json; charset=utf-8");
echo $json_string;

受信

$json_string = file_get_contents('php://input');
$data = json_decode($json_string);

.NET Framework (ASP.NET MVC)

C# でのコード例です。

送信

コントローラで...

public class MyController : Controller {
  //...
  public ActionResult Index()
  {
    //...
    return Json(data);
  }
}

受信

こちらもコントローラで...

public class MyController : Controller {
  //...
  // DataClass クラス(例)では、受け取りたいJSONデータの構造が定義されています。

  [HttpPost] // [HttpGet]でも、指定しない場合も可
  public ActionResult Index(DataClass data)
  {
    //...
  }
}
11
11
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
11
11