Главная страница  /  Занятия  /  #17  /  Создание асинхронного AJAX-запроса методом POST

Создание асинхронного AJAX-запроса методом POST

Задание:

Продемонстрировать, как осуществляется асинхронный AJAX-запрос методом POST.

html-документ (index.html):

   <!DOCTYPE html>
   
   <html lang="ru">
   
    <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Асинхронный AJAX-запрос методом POST</title>
     <script src="scripts.js"></script>
    </head>
   
    <body>
     <div></div>
     <input type="text" value="">
     <button>Получить курс валюты с&nbsp;сайта ЦБ&nbsp;РФ</button>
    </body>
   
   </html>

JS–скрипты (scripts.js):

   var xhr = new XMLHttpRequest();
      
   window.onload = function()
   {
    document.body.children[1].onkeydown = function(e) { if(e.keyCode == 13) { sendAjaxRequestByPOST(); } };
    document.body.children[2].onclick = sendAjaxRequestByPOST;
   };
   
   function sendAjaxRequestByPOST()
   {
    xhr.open("POST", "scripts.php", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); xhr.responseType = 'text'; xhr.send("currency="+encodeURIComponent(document.body.children[1].value)); }; xhr.onload = function() { document.body.children[0].innerHTML = xhr.response; };

PHP–скрипты (scripts.php):

   <?
    header('Content-Type: text/html; charset=utf-8');
    $cbrLink = 'http://www.cbr.ru/scripts/XML_daily.asp?date_req='.date("d/m/Y");;
    $xmlContent = simplexml_load_file($cbrLink);
    foreach($xmlContent as $Valute)
    {
     if(preg_match("/{$_POST['currency']}/iu", $Valute->CharCode, $matchArray) || preg_match("/{$_POST['currency']}/iu", $Valute->Name, $matchArray))
     {
      echo 'Дата: '.$xmlContent['Date'].'<br>Валюта: '.$Valute->Name.' ('.$Valute->CharCode.')<br>Номинал: '.$Valute->Nominal.'<br>Курс: '.$Valute->Value.' руб.<br><br>';
      return;
     }
    }
    echo 'Валюта не&nbsp;найдена<br><br>';
   ?>

Результат:

Результат выполнения задания можно посмотреть здесь.