LoginSignup
9
18

More than 5 years have passed since last update.

jQueryを使わないでAjax(text, XML, JSON対応)

Last updated at Posted at 2017-09-29

GETリクエスト/Textレスポンス その1

HTML
<h1>Custom Boards Report</h1>
<div id="boards">
  <table>
    <tr><th>Snowboards Sold</th>
    <td><span id="boards-sold">1012</span></td></tr>
    <tr><th>What I Sell 'em For</th>
    <td>$<span id="price">249.95</span></td></tr>
    <tr><th>What it Costs Me</th>
    <td>$<span id="cost">84.22</span></td></tr>
  </table>
  <h2>Cash for the Slopes: 
  $<span id="cash">167718.76</span></h2>
  <form method="GET" action="getUpdatedBoardSales.php">
    <input id="submit" value="Show Me the Money" type="button" />
  </form>
</div>
CSS
body {
  font-family:     Verdana, Geneva, Arial, sans-serif;
  font-size:       small;
  text-align:      center;
}

h1 {
  color:           #cc6600;
  border-bottom:   thin dotted #888888;
  font-size:       1.7em;
}

h2 {
  font-size:       1.3em;
}

table {
  margin-left:     auto;
  margin-right:    auto;
  border:          thin solid black;
  caption-side:    bottom;
  border-collapse: collapse;
  font-size:       small;
}

td, th {
  border:          thin dotted grey;
  padding:         5px;
  text-align:      center;
}

th {
 background-color: #fcba7a;
}
JavaScript
// リクエストオブジェクト格納用に変数を初期化
var request = null;

// イベントリスナー
document.getElementById('submit').addEventListener('click', function() {
  getBoardsSold();
}, false);

// リクエストオブジェクト作成(IEクロスブラウザ対策有り)
function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject('Msxm12.XMLHTTP');
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject('Microsoft.XMLHTTP');
      } catch (failed) {
        request = null;
      }
    }
  }

  if (request === null) {
    alert('エラー! requestオブジェクトの作成に失敗しました。');
  }
}

// リクエスト送信
function getBoardsSold() {
  createRequest();
  request.open('GET', './getUpdatedBoardSales-ajax.php', true);
  request.onreadystatechange = updatePage;
  request.send(null);
}

// レスポンス処理
function updatePage() {
  if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
    var newTotal              = request.responseText;
    var boardsSoldElm         = document.getElementById('boards-sold');
    var cashElm               = document.getElementById('cash');
    boardsSoldElm.textContent = newTotal;

    var price        = document.getElementById('price');
    var cost         = document.getElementById('cost');
    var costPerBoard = parseFloat(price.textContent) - parseFloat(cost.textContent);
    var totalProfit  = costPerBoard * parseFloat(boardsSoldElm.textContent);

    cashElm.textContent = totalProfit;
  }
}
PHP(ダミーの値を出力)
<?php

// Start with an arbitrary number of boards sold
$totalSold = 1012;

// Reflect new sales
srand((double)microtime() * 1000000);
$totalSold = $totalSold + rand(0,1000);

echo $totalSold;

?>

GETリクエスト/Textレスポンス その2

HTML
 <body onLoad="document.forms[0].reset();">
  <p><img src="./breakneck-logo.gif" alt="Break Neck Pizza" /></p>
  <form method="POST" action="placeOrder.php">
   <p>Enter your phone number:
    <input id="phone" type="text" size="14" name="phone" />
   </p>
   <p>Your order will be delivered to:</p>
   <p><textarea id="address" name="address" rows="4" cols="50"></textarea></p>
   <p>Type your order in here:</p>
   <p><textarea id="order" name="order" rows="6" cols="50"></textarea></p>
   <p><input id="submit" type="submit" value="Order Pizza" /></p>
  </form>
CSS
body {
  color: darkred;
  font-family: sans-serif;
  margin: 2em;
  padding: 1em;
  border: double darkred;
}

.customer-info {
  font-weight: bold;
}

.customer-data {
  color: black;
}
JavaScript
document.getElementById('phone').addEventListener('change', function() {
  getCustomerInfo();
}, false); 

// リクエストオブジェクト作成(IEクロスブラウザ対策有り)
var request = null;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject('Msxm12.XMLHTTP');
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject('Microsoft.XMLHTTP');
    } catch (failed) {
      request = null;
    }
  }
}

if (request === null) {
  window.alert('エラー! requestオブジェクトの作成に失敗しました。');
}

// リクエスト送信
function getCustomerInfo() {
  request.open(
    'GET',
    './lookupCustomer.php?phone=' + escape(document.getElementById('phone').value),
    true
  );
  request.onreadystatechange = updatePage   ;
  request.send(null);
}

// レスポンス処理
function updatePage() {
  if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
    document.getElementById('address').value = request.responseText;
  }
}
PHP(ダミーの値を出力)
<?php

class Customer {
  var $name, $street, $city, $state, $zipCode;

  function Customer($name, $street, $city, $state, $zipCode) {
    $this->name = $name;
    $this->street = $street;
    $this->city = $city;
    $this->state = $state;
    $this->zipCode = $zipCode;
  }

  function getName() {
    return $this->name;
  }

  function getAddress() {
    return $this->street . "\n" .
           $this->city . ", " .
           $this->state . " " .
           $this->zipCode;
  }
}

// Set up some addresses to use
$customers[0] = new Customer("Doug Henderson",
                             "7804 Jumping Hill Lane",
                             "Dallas", "Texas", "75218");
$customers[1] = new Customer("Mary Jenkins",
                             "7081 Teakwood #24C",
                             "Dallas", "Texas", "75182");
$customers[2] = new Customer("John Jacobs",
                             "234 East Rutherford Drive",
                             "Topeka", "Kansas", "66608");
$customers[3] = new Customer("Happy Traum",
                             "876 Links Circle",
                             "Topeka", "Kansas", "66608");

// Pick a customer
srand((double)microtime() * 1000000);
$customerId = rand(0,3);
$customer = $customers[$customerId];

echo $customer->getName() . "\n" .
     $customer->getAddress();

?>

GETリクエスト/Textレスポンス その3(複数のインスタンスを管理する)

HTML
<body onload="document.forms[0].reset();">
  <div id="header">
    <h1>Ajax-powered Coffee Maker</h1>
  </div>

  <div id="wrapper">
   <div id="coffeemaker1">
    <h2>Coffee Maker #1</h2>
    <p><img src="images/CoffeeMaker1.gif" alt="Coffee Maker #1" /></p>
    <div id="coffeemaker1-status">Idle</div>
   </div>

   <div id="coffeeorder">
    <p><img src="images/coffeeMugWithBeans.jpg" alt="Coffee Pot 1" /></p>
    <h2>Place your coffee order here:</h2>
    <div id="controls1">
     <form>
      <p>Name: <input type="text" name="name" id="name" /></p>
      <h3>Size</h3>
      <p> 
       <input type="radio" name="size" 
              value="small" checked="true">Small</input>
       &nbsp;&nbsp;
       <input type="radio" name="size" 
              value="medium">Medium</input>
       &nbsp;&nbsp;
       <input type="radio" name="size" 
              value="large">Large</input>
      </p>
      <h3>Beverage</h3>
      <p> 
       <input type="radio" name="beverage" 
              value="mocha" checked="true">Mocha</input>
       &nbsp;&nbsp;
       <input type="radio" name="beverage" 
              value="latte">Latte</input>
       &nbsp;&nbsp;
       <input type="radio" name="beverage" 
              value="cappucino">Cappucino</input>
      </p>
      <p>
       <input type="button" id="submit" value="Order Coffee" />
      </p>
     </form>
    </div>
   </div>

   <div id="coffeemaker2">
    <h2>Coffee Maker #2</h2>
    <p><img src="images/CoffeeMaker2.gif" alt="Coffee Maker #2" /></p>
    <div id="coffeemaker2-status">Idle</div>
   </div>

   <p id="clear"></p>
  </div>
CSS
body {
  font-family: "Lucida Grande", Verdana, Arial, sans-serif;
  text-align: center;
  font-size: small;
  margin: 10px;
  background-color: silver;
}

h1 {
  font-size: 140%;
}

h2 {
  font-size: 120%;
  padding-top: 10px;
}

h3 {
  font-size: 100%;
  text-decoration: underline;
}

p {
  margin-bottom: 20px;
}

img {
  height: 100px;
  padding: 10px;
}

form {
  margin-top: 20px;
}

div#wrapper {
  position: relative;
  width: 746px;
  margin: 10px auto;
  padding: 10px;
  color: #333;
  background-color: white;
  border: 1px solid black;
}

div#coffeeorder {
  position: relative;
  top: 60px;
  left: 220px;
  width: 300px;
  margin: 0;
  padding: 10px;
}

div#coffeemaker1 {
  position: absolute;
  top: 10px;
  padding: 10px;
  width: 200px;
  background-color: #f5f5f5;
  border:double medium black;
  left: 10px;
}

div#coffeemaker2 {
  position: absolute;
  top: 10px;
  margin-left: 520px;
  padding: 10px;
  width: 200px;
  background-color: #f5f5f5;
  border:double medium black;
  float: right;
}

#clear {
  clear: both;
}
JavaScript
document.getElementById('submit').addEventListener('click', function() {
  orderCoffee();
  document.forms[0].reset();
}, false); 

// リクエストオブジェクト作成(IEクロスブラウザ対策有り)
function createRequest() {
  var request = null;
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject('Msxm12.XMLHTTP');
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject('Microsoft.XMLHTTP');
      } catch (failed) {
        request = null;
      }
    }
  }

  if (request === null) {
    window.alert('エラー! requestオブジェクトの作成に失敗しました。');
  } else {
    return request;
  }
}
var request1 = createRequest();
var request2 = createRequest();

// 注文内容の設定
function orderCoffee() {
  var name         = document.getElementById('name').value;
  var beverage     = document.forms[0].beverage.value;
  var size         = document.forms[0].size.value;
  var coffeemaker1 = document.getElementById('coffeemaker1-status');
  var coffeemaker2 = document.getElementById('coffeemaker2-status');
  var url          = './coffeemaker.php?';

  if (coffeemaker1.textContent === 'Idle') {
    coffeemaker1.textContent = name + '' + size + beverage + 'を作っています';
    url = url
          + 'name=' + escape(name)
          + '&beverage='+ escape(beverage)
          + '&size=' + escape(size)
          + '&coffeemaker=1';
    sendRequest(request1, url);

  } else if (coffeemaker2.textContent === 'Idle') {
    coffeemaker2.textContent = name + '' + size + beverage + 'を作っています';
    url = url
          + 'name=' + escape(name)
          + '&beverage='+ escape(beverage)
          + '&size=' + escape(size)
          + '&coffeemaker=2';
    sendRequest(request2, url);

  } else {
    window.alert('ちょっと待ってね!');
  }
}

// リクエスト送信
function sendRequest(request, url) {
  request.onreadystatechange = serveDrink;
  request.open('GET', url, true);
  request.send(null);
}

// レスポンス処理
function serveDrink() {
  if (request1.readyState === XMLHttpRequest.DONE && request1.status === 200) {
    // コーヒーが出来上がったことをalertでお知らせ
    var name = request1.responseText.substring(1, request1.responseText.length);
    window.alert(name + 'さんのコーヒーが出来上がりました!');

    // コーヒーメーカーを待機状態に戻す
    document.getElementById('coffeemaker' + request1.responseText[0] + '-status').textContent = 'Idle';

    // requestオブジェクトを初期化(初期化しないとこのifがtrueのままとなり、request2が処理されなくなる)
    request1 = createRequest();

  } else if(request2.readyState === XMLHttpRequest.DONE && request2.status === 200) {
    // コーヒーが出来上がったことをalertでお知らせ
    var name = request2.responseText.substring(1, request2.responseText.length);
    window.alert(name + 'さんのコーヒーが出来上がりました!');

    // コーヒーメーカーを待機状態に戻す
    document.getElementById('coffeemaker' + request2.responseText[0] + '-status').textContent = 'Idle';

    // requestオブジェクトを初期化
    request2 = createRequest();
  }
}
PHP
<?php

$name = $_REQUEST['name'];
$size = $_REQUEST['size'];
$beverage = $_REQUEST['beverage'];
$coffeemaker = $_REQUEST['coffeemaker'];

for ($i = 0; $i < 300000000; $i++) {
  // brewing
}

echo $coffeemaker . $name;

?>

POSTリクエスト/Textレスポンス

HTML
<body onLoad="document.forms[0].reset();">
  <div id="main-page">
   <p><img src="breakneck-logo_new.gif" alt="Break Neck Pizza" /></p>
   <form id="order-form">
    <p>Enter your phone number:
     <input type="text" size="14" 
            name="phone" id="phone" />
    </p>
    <p>Type your order in here:</p>
    <p>
      <textarea name="order" id="order" rows="6" cols="50"></textarea>
    </p>
    <p>Your order will be delivered to:</p>
    <p>
      <textarea name="address" id="address" rows="4" cols="50"></textarea>
    </p>
    <p>
      <input type="button" id="submit" value="Order Pizza" />
    </p>
   </form>
   <p class="tagline">** No more waiting! Now faster than ever! **</p>
  </div>
CSS
body {
  color: darkred;
  font-family: "Geneva", sans-serif;
  font-size: 14;
  margin: 2em;
}

p {
  margin: 1.8em;
}

#main-page {
  border: double darkred;
  padding: 1em;
}

.customer-info {
  font-weight: bold;
}

.customer-data {
  color: black;
}

.tagline {
  text-align: center;
  color: black;
  font-size: .8em;
  font-style: italic;
}
JavaScript
document.getElementById('phone').addEventListener('change', function() {
  getCustomerInfo()
}, false);

document.getElementById('submit').addEventListener('click', function() {
  submitOrder();
}, false);

// リクエストオブジェクト作成(IEクロスブラウザ対策有り)
var request = null;

try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = null;
    }
  }
}

if (request == null) {
  window.alert("Error creating request object!");
}

function getCustomerInfo() {
  var phone = document.getElementById("phone").value;
  var url = "lookupCustomer.php?phone=" +
            escape(phone);
  request.open("GET", url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}

function updatePage() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      /* Get the response from the server */
      var customerAddress = request.responseText;

      /* Update the HTML web form */
      document.getElementById("address").value = customerAddress;
    } else
      window.alert("Error! Request status is " + request.status);
  }
}

function submitOrder() {
  var phone   = document.getElementById('phone').value;
  var address = document.getElementById('address').value;
  var order   = document.getElementById('order').value;
  var url     = 'placeOrder.php';

  request.open('POST', url, true);
  request.onreadystatechange = showConfirmation;
  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // POST時はコンテンツタイプ設定が必要
  request.send('phone=' + escape(phone)
               + '&address=' + escape(address)
               + '&order=' + escape(order));
}

function showConfirmation() {
  if (request.readyState === XMLHttpRequest.DONE) {
    if (request.status === 200) {
      // ページ上のフォームの場所を特定する
      var mainDiv   = document.getElementById('main-page');
      var orderForm = document.getElementById('order-form');

      // 注文確認のテキストを作成する
      pElement             = document.createElement('p');
      pElement.textContent = 'ご注文いただいたピザは、あと'
                            + request.responseText
                            + '分で到着します。ありがとうございました!'

      // フォームを注文確認と差し替える
      mainDiv.replaceChild(pElement, orderForm);

    } else {
      var message = request.getResponseHeader('Status');
      if ((message.length === null) || (message.length <= 0)) {
        window.alert('エラー!リクエストステータス:' + request.status);
      } else {
        window.alert(message);
      }
    }
  }
}
lookupCustomer.php(ダミーの値を出力)
<?php

class Customer {
  var $name, $street, $city, $state, $zipCode;

  function __construct($name, $street, $city, $state, $zipCode) {
    $this->name = $name;
    $this->street = $street;
    $this->city = $city;
    $this->state = $state;
    $this->zipCode = $zipCode;
  }

  function getName() {
    return $this->name;
  }

  function getAddress() {
    return $this->street . "\n" .
           $this->city . ", " .
           $this->state . " " .
           $this->zipCode;
  }
}

// Set up some addresses to use
$customers[0] = new Customer("Doug Henderson",
                             "7804 Jumping Hill Lane",
                             "Dallas", "Texas", "75218");
$customers[1] = new Customer("Mary Jenkins",
                             "7081 Teakwood #24C",
                             "Dallas", "Texas", "75182");
$customers[2] = new Customer("John Jacobs",
                             "234 East Rutherford Drive",
                             "Topeka", "Kansas", "66608");
$customers[3] = new Customer("Happy Traum",
                             "876 Links Circle",
                             "Topeka", "Kansas", "66608");

// Pick a customer
srand((double)microtime() * 1000000);
$customerId = rand(0,3);
$customer = $customers[$customerId];

echo $customer->getName() . "\n" .
     $customer->getAddress();

?>
placeOrder.php
<?php

include("order.php");
include("delivery.php");

// Error checking
$order = $_REQUEST['order'];
$address = $_REQUEST['address'];
if (strlen($order) <= 0) {
  header("Status: No order was received.", true, 400);
  echo " ";
  exit;
}
if (strlen($address) <= 0) {
  header("Status: No address was received.", true, 400);
  echo " ";
  exit;
} 


// Place the order
$pizzaOrder = new PizzaOrder($order, $address);
$pizzaOrder->cookOrder();
$pizzaOrder->prepOrder();

// Deliver the order
$delivery = new Delivery($pizzaOrder);
$delivery->deliver();
$deliveryTime = $delivery->getDeliveryEstimate();

echo $deliveryTime;
?>
order.php
<?php

class PizzaOrder {
  var $order, $address, $status;

  function __construct($order, $address) {
    $this->order = $order;
    $this->address = $address;
    $this->status = "In Progress";
    srand((double)microtime() * 1000000);
  }

  function cookOrder() {
    $this->status = "Cooking";
    $cookTime = rand(0, 100000);
    for ($i=0; $i<$cookTime; $i++) {
      // cook order
    }
    $this->status = "Cooked and ready for prepping";
  }

  function prepOrder() {
    $this->status = "Preparing for Delivering";
    $prepTime = rand(0, 100000);
    for ($i=0; $i<$prepTime; $i++) {
      // prepare for delivery
    }
    $this->status = "Prepped for Delivery";
  }

  function getStatus() {
    return $this->status;
  }
}

?>
delivery.php
<?php

class Delivery {
  var $status, $pizzaOrder, $deliveryEstimate;

  function __construct($pizzaOrder) {
    $this->pizzaOrder = $pizzaOrder;
    $this->status = "Received Order";
  }

  function deliver() {
    if ($this->pizzaOrder->getStatus() == "Prepped for Delivery") {
      srand((double)microtime() * 1000000);
      $this->deliveryEstimate = rand(2, 10);
      $this->status = "Delivering Order";
      for ($i = 0; $i<$deliveryEstimate; $i++) {
        // Deliver pizza
      }
      $status = "Pizza Delivered.";
    } else {
      $this->pizzaOrder->prepOrder();
      $this->deliver();
    }
  }

  function getStatus() {
    return $this->status;
  }

  function getDeliveryEstimate() {
    return $this->deliveryEstimate;
  }
}

GETリクエスト/XMLレスポンス

HTML
<h1>How Much Butt We're Kicking</h1>
  <div id="boards">
   <table>
    <tr><th>Snowboards Sold</th>
     <td><span id="boards-sold">1672</span></td></tr>
    <tr><th>What I Sell 'em For</th>
     <td>$<span id="boards-price">249.95</span></td></tr>
    <tr><th>What it Costs Me</th>
     <td>$<span id="boards-cost">84.22</span></td></tr>
   </table>
   <table>
    <tr><th>Boots Sold</th>
     <td><span id="boots-sold">312</span></td></tr>
    <tr><th>What I Sell 'em For</th>
     <td>$<span id="boots-price">175.47</span></td></tr>
    <tr><th>What it Costs Me</th>
     <td>$<span id="boots-cost">54.23</span></td></tr>
   </table>
   <table>
    <tr><th>Bindings Sold</th>
     <td><span id="bindings-sold">82</span></td></tr>
    <tr><th>What I Sell 'em For</th>
     <td>$<span id="bindings-price">146.92</span></td></tr>
    <tr><th>What it Costs Me</th>
     <td>$<span id="bindings-cost">98.03</span></td></tr>
   </table>
   <h2>Cash for the Slopes: 
    $<span id="cash">318936.42</span></h2>
   <form method="GET">
    <input value="Show Me the Money" type="button" 
           onClick="getNewTotals();" /> 
   </form>
</div>
CSS
body {
  font-family:     Verdana, Geneva, Arial, sans-serif;
  font-size:       small;
  text-align:      center;
}

h1 {
  color:           #cc6600;
  border-bottom:   thin dotted #888888;
  font-size:       1.7em;
}

h2 {
  font-size:       1.3em;
}

table {
  margin-left:     auto;
  margin-right:    auto;
  border:          thin solid black;
  caption-side:    bottom;
  border-collapse: collapse;
  font-size:       small;
}

td, th {
  border:          thin dotted grey;
  padding:         5px;
  text-align:      center;
}

th {
 background-color: #fcba7a; 
}
JavaScript
// リクエストオブジェクトを作成
var request = null;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = null;
    }
  }
}

if (request == null) {
  alert("Error creating request object!");
}

function getNewTotals() {
  var url = "getUpdatedSales.php";
  url = url + "?dummy=" + new Date().getTime();
  request.open("GET", url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}

function updatePage() {
  if (request.readyState === XMLHttpRequest.DONE) {
    if (request.status === 200) {
      // XMLレスポンスから最新の販売数合計を取得する
        // ボード合計数
      var totalBoards = request.responseXML.getElementsByTagName('boards-sold')[0].textContent;
        // ブーツ合計数
      var totalBoots = request.responseXML.getElementsByTagName('boots-sold')[0].textContent;
        // バインディング合計数
      var totalBindings = request.responseXML.getElementsByTagName('bindings-sold')[0].textContent;

      // ページ内各商品の合計数をXML取得結果に更新
        // ボード
      document.getElementById('boards-sold').textContent = totalBoards;
        // ブーツ
      document.getElementById('boots-sold').textContent = totalBoots;
        // バインディング
      document.getElementById('bindings-sold').textContent = totalBindings;

      // 各商品の売上算出→売上を更新
        // ボード
      var boardsPrice = parseInt(document.getElementById('boards-price').textContent);
      var boardsCost  = parseInt(document.getElementById('boards-cost').textContent);
      var boardsCash  = (boardsPrice - boardsCost) * totalBoards;
        // ブーツ
      var bootsPrice = parseInt(document.getElementById('boots-price').textContent);
      var bootsCost  = parseInt(document.getElementById('boots-cost').textContent);
      var bootsCash  = (bootsPrice - bootsCost) * totalBoots;
        // バインディング
      var bindingsPrice = parseInt(document.getElementById('bindings-price').textContent);
      var bindingsCost  = parseInt(document.getElementById('bindings-cost').textContent);
      var bindingsCash  = (bindingsPrice - bindingsCost) * totalBindings;
        // 合計売上金額
      var cash = boardsCash + bootsCash + bindingsCash;
      cash     = Math.round(cash * 100) / 100;
      document.getElementById('cash').textContent = cash;

    } else {
      window.alert('エラー!リクエストステータス:' + request.status);
    }
  }
}
PHP(XMLでダミーの値を出力)
<?php

// Start with an arbitrary number of sales
$bootsSold = 1672;
$boardsSold = 312;
$bindingsSold = 82;

// Reflect new sales
srand((double)microtime() * 1000000);
$bootsSold = $bootsSold + rand(0,10);
$boardsSold = $boardsSold + rand(0,5);
$bindingsSold = $bindingsSold + rand(0,3);

header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
?>

<totals>
 <boards-sold><? echo $boardsSold; ?></boards-sold>
 <boots-sold><? echo $bootsSold; ?></boots-sold>
 <bindings-sold><? echo $bindingsSold; ?></bindings-sold>
</totals>

GETリクエスト/JSONレスポンス(PHP)

HTML
<html lang="en">
  <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <button id="exec">button</button>

    <script>
      ...
    </script>
  </body>
</html>
JavaScript
document.getElementById('exec').addEventListener('click', function() {
  var ajax = null;
  try {
    ajax = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      ajax = new ActiveXObject("Msxml2.XMLHTTP"); // IE用
    } catch (othermicrosoft) {
      try {
        ajax = new ActiveXObject("Microsoft.XMLHTTP"); // IE用
      } catch (failed) {
        ajax = null;
      }
    }
  }

  if (ajax == null) {
    window.alert("Error creating request object!");
  }

  ajax.open('GET', 'ajax.php', true);
  ajax.onreadystatechange = update;
  ajax.send(null);

  function update() {
    if(ajax.readyState === XMLHttpRequest.DONE) {
      if(ajax.status === 200) {
        $jsonData = JSON.parse(ajax.responseText);

        var ul = document.createElement('ul');

        for (var i = 0; i < $jsonData.totals.length; i++) {
          var li = document.createElement('li');
          li.textContent = $jsonData.totals[i].location;
          ul.appendChild(li);
        }

        document.body.insertBefore(ul, document.body.firstElementChild);

      } else {
        var message = request.getResponseHeader("Status");
        if ((message.length == null) || (message.length <= 0)) {
          alert("Error! Request status is " + request.status);
        } else {
          alert(message);
        }
      }  
    }
  }
}, false);
PHP
<?php

$vail = [
  'location'     => 'Vail', 
  'boardsSold'   => 100,
  'bootsSold'    => 100,
  'bindingsSold' => 100
];
$santaFe = [
  'location'     => 'Santa Fe', 
  'boardsSold'   => 200,
  'bootsSold'    => 200,
  'bindingsSold' => 200
];
$boulder = [
  'location'     => 'Boulder', 
  'boardsSold'   => 300,
  'bootsSold'    => 300,
  'bindingsSold' => 300
];
$denver = [
  'location'     => 'Denver', 
  'boardsSold'   => 400,
  'bootsSold'    => 400,
  'bindingsSold' => 400
];
$totals = [
    'totals' => [
        $vail, $santaFe, $boulder, $denver
    ]
];

$output = json_encode($totals);
echo $output;

?>

GETリクエスト/JSONレスポンス

<h1>Boards 'R' Us :: How Much Butt We're Kicking</h1>
  <div id="boards">
   <table>
    <tr><th>Snowboards Sold</th>
     <td><span id="boards-sold">1672</span></td></tr>
    <tr><th>What I Sell 'em For</th>
     <td>$<span id="boards-price">249.95</span></td></tr>
    <tr><th>What it Costs Me</th>
     <td>$<span id="boards-cost">84.22</span></td></tr>
   </table>
   <table>
    <tr><th>Boots Sold</th>
     <td><span id="boots-sold">312</span></td></tr>
    <tr><th>What I Sell 'em For</th>
     <td>$<span id="boots-price">175.47</span></td></tr>
    <tr><th>What it Costs Me</th>
     <td>$<span id="boots-cost">54.23</span></td></tr>
   </table>
   <table>
    <tr><th>Bindings Sold</th>
     <td><span id="bindings-sold">82</span></td></tr>
    <tr><th>What I Sell 'em For</th>
     <td>$<span id="bindings-price">146.92</span></td></tr>
    <tr><th>What it Costs Me</th>
     <td>$<span id="bindings-cost">98.03</span></td></tr>
   </table>
   <h2>Cash for the Slopes: 
    $<span id="cash">318936.42</span></h2>
   <form method="GET">
    <input value="Show Me the Money" type="button" 
           onClick="getNewTotals();" /> 
   </form>
  </div>
CSS
body {
  font-family:     Verdana, Geneva, Arial, sans-serif;
  font-size:       small;
  text-align:      center;
}

h1 {
  color:           #cc6600;
  border-bottom:   thin dotted #888888;
  font-size:       1.7em;
}

h2 {
  font-size:       1.3em;
}

table {
  margin-left:     auto;
  margin-right:    auto;
  border:          thin solid black;
  caption-side:    bottom;
  border-collapse: collapse;
  font-size:       small;
}

td, th {
  border:          thin dotted grey;
  padding:         5px;
  text-align:      center;
}

th {
 background-color: #fcba7a; 
}
JavaScript
var request = null;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = null;
    }
  }
}

if (request == null) {
  window.alert("Error creating request object!");
}

function getNewTotals() {
  var url = "getUpdatedSales.php";
  url = url + "?dummy=" + new Date().getTime();
  request.open("GET", url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}

function updatePage() {
  if (request.readyState === XMLHttpRequest.DONE) {
    if (request.status === 200) {
      // JSONレスポンスから最新の販売数合計を取得する
      var jsonData = JSON.parse(request.responseText);
        // ボード合計数
      var totalBoards = jsonData.totals[0].boardsSold
                        + jsonData.totals[1].boardsSold
                        + jsonData.totals[2].boardsSold
                        + jsonData.totals[3].boardsSold;
        // ブーツ合計数
      var totalBoots = jsonData.totals[0].bootsSold
                       + jsonData.totals[1].bootsSold
                       + jsonData.totals[2].bootsSold
                       + jsonData.totals[3].bootsSold;
        // バインディング合計数
      var totalBindings = jsonData.totals[0].bindingsSold
                          + jsonData.totals[1].bindingsSold
                          + jsonData.totals[2].bindingsSold
                          + jsonData.totals[3].bindingsSold;

      // ページ内各商品の合計数をXML取得結果に更新
        // ボード
      document.getElementById('boards-sold').textContent = totalBoards;
        // ブーツ
      document.getElementById('boots-sold').textContent = totalBoots;
        // バインディング
      document.getElementById('bindings-sold').textContent = totalBindings;

      // 各商品の売上算出→売上を更新
        // ボード
      var boardsPrice = parseInt(document.getElementById('boards-price').textContent);
      var boardsCost  = parseInt(document.getElementById('boards-cost').textContent);
      var boardsCash  = (boardsPrice - boardsCost) * totalBoards;
        // ブーツ
      var bootsPrice = parseInt(document.getElementById('boots-price').textContent);
      var bootsCost  = parseInt(document.getElementById('boots-cost').textContent);
      var bootsCash  = (bootsPrice - bootsCost) * totalBoots;
        // バインディング
      var bindingsPrice = parseInt(document.getElementById('bindings-price').textContent);
      var bindingsCost  = parseInt(document.getElementById('bindings-cost').textContent);
      var bindingsCash  = (bindingsPrice - bindingsCost) * totalBindings;
        // 合計売上金額
      var cash = boardsCash + bootsCash + bindingsCash;
      cash     = Math.round(cash * 100) / 100;
      document.getElementById('cash').textContent = cash;

    } else {
      var message = request.getResponseHeader("Status");
      if ((message.length == null) || (message.length <= 0)) {
        window.alert("Error! Request status is " + request.status);
      } else {
        window.alert(message);
      }
    }
  }
}
PHP(JSONでダミーの値を出力)
<?php

// Start with an arbitrary number of sales
$bootsSold = 1672;
$boardsSold = 312;
$bindingsSold = 82;

// Reflect new sales
srand((double)microtime() * 1000000);
$bootsSold = $bootsSold + rand(0,10);
$boardsSold = $boardsSold + rand(0,5);
$bindingsSold = $bindingsSold + rand(0,3);

$vailBoards = $boardsSold/4;
$vailBoots = $bootsSold/4;
$vailBindings = $bindingsSold/4;
$santaFeBoards = $boardsSold/4;
$santaFeBoots = $bootsSold/4;
$santaFeBindings = $bindingsSold/4;
$boulderBoards = $boardsSold/4;
$boulderBoots = $bootsSold/4;
$boulderBindings = $bindingsSold/4;
$denverBoards = $boardsSold/4;
$denverBoots = $bootsSold/4;
$denverBindings = $bindingsSold/4;

$vail = [
    'location'     => 'Vail', 
    'boardsSold'   => $vailBoards,
    'bootsSold'    => $vailBoots,
    'bindingsSold' => $vailBindings
];
$santaFe = [
    'location'     => 'Santa Fe', 
    'boardsSold'   => $santaFeBoards,
    'bootsSold'    => $santaFeBoots,
    'bindingsSold' => $santaFeBindings
];
$boulder = [
    'location'     => 'Boulder', 
    'boardsSold'   => $boulderBoards,
    'bootsSold'    => $boulderBoots,
    'bindingsSold' => $boulderBindings
];
$denver = [
    'location'     => 'Denver', 
    'boardsSold'   => $denverBoards,
    'bootsSold'    => $denverBoots,
    'bindingsSold' => $denverBindings
];
$totals = [
  'totals' => [
      $vail, $santaFe, $boulder, $denver
  ]
];

$output = json_encode($totals);
echo $output;

?>
9
18
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
9
18