<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Получение ответа сервера в текстовом, XML и JSON форматах</title>
<script src="scripts.js"></script>
</head>
<body>
<select>
<option value="text">Текст</option>
<option value="document">XML</option>
<option value="json">JSON</option>
</select>
<button>Отправить запрос</button>
</body>
</html>
var xhr = new XMLHttpRequest();
window.onload = function()
{
document.body.children[1].onclick = sendAjaxRequest;
};
function sendAjaxRequest()
{
xhr.open("GET", "scripts.php?answertype="+document.body.children[0].value, true);
xhr.responseType = document.body.children[0].value;
xhr.send();
};
xhr.onload = function()
{
switch(xhr.responseType)
{
case 'text':
alert(xhr.response);
break;
case 'document':
alert(xhr.response.firstChild.tagName+'|'+xhr.response.firstChild.innerHTML);
break;
case 'json':
for(var index in xhr.response) alert(index+'|'+xhr.response[index]);
break;
default:
break;
}
};
<?
switch($_GET['answertype'])
{
case "text":
header('Content-Type: text/plain; charset=utf-8');
echo 'Name|Vasya';
break;
case "document":
header('Content-Type: text/xml; charset=utf-8');
echo '<?xml version="1.0"?><Name>Vasya</Name>';
break;
case "json":
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('Name' => 'Vasya'));
break;
default:
header('Content-Type: text/plain; charset=utf-8');
echo 'Неизвестный формат ответа';
break;
}
?>
Результат выполнения задания можно посмотреть
здесь.