@DiaTMss

Возможно ли спарсить на клиенте json и html одновременно?

Доброго времени суток программисты. Вообщем проблема в том что я могу получить на клиенте либо html либо json
мне нужно без перезагрузки страницы обновить часть страницы и в тоже время обновить title

Пока всё примитивно демка, но в будущем реализую что то типо того

/*
		$router->get($uri, $callback);
		$router->post($uri, $callback);
		$router->put($uri, $callback);
		$router->patch($uri, $callback);
		$router->delete($uri, $callback);
		$router->options($uri, $callback);
	*/


5d171653d15db061732101.png

(function()
{
	var xhr     = new XMLHttpRequest();
	var tabMenu   = document.getElementById('tabMenu');
	var fh5comain = document.getElementById('fh5co-main');

	var getContent = function()
	{
		if (xhr.readyState === 4)
		{
			if (xhr.status === 200)
			{
				fh5comain.innerHTML = xhr.responseText;
			}

			else console.log(xhr.status + ' ' + xhr.statusText);
		}
	};

	/*
	function getUpdate()
	{
		var getTitle = function()
		{
			if (xhr.readyState === 4)
			{
				if (xhr.status === 200)
				{
					var jText = JSON.parse(xhr.responseText);

					document.title = jText.title;
				}

				else console.log(xhr.status + ' ' + xhr.statusText);
			}
		};

		getAjax('GET', '/api' + location.pathname, null, getTitle);
	}
	*/

	for(var tM = 0; tM < tabMenu.children.length; tM++)
	{
		tabMenu.children[tM].children[0].onclick = function()
		{
			history.pushState(null, null, this.href);

			getAjax('GET', location.pathname, null, getContent);

			return false;
		}
	}
window.onpopstate = function()
	{
		getAjax('GET', location.pathname, null, getContent);
	}

	function getAjax(method, uri, params, action)
	{
		if (xhr)
		{
			xhr.open(method, uri, true);

			xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

			xhr.onreadystatechange = action;

			xhr.send(params);
		}
	}
}());


<?php

	function isAjax()
	{
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) return true;
		else false;
	}

	$uri      = (isAjax()) ? $_SERVER['REQUEST_URI'] : $_SERVER['REQUEST_URI']; 
	$template = null;
	$title    = null;

	if ($uri === '/')
	{
		$title = 'Home';

		if(isAjax())
		{
			$template = array
			(
				'contentHome'
			);
		}

		else
		{
			$template = array
			(
				'header',
				'menu',
				'contentHome',
				'footer'
			);
		}
	}

	else if ($uri === '/blog')
	{
		$title = 'Blog';

		if(isAjax())
		{
			$template = array
			(
				'contentBlog'
			);
		}

		else
		{
			$template = array
			(
				'header',
				'menu',
				'contentBlog',
				'footer'
			);
		}
	}

	else if ($uri === '/portfolio')
	{
		$title = 'Portfolio';

		if(isAjax())
		{
			$template = array
			(
				'contentPortfolio'
			);
		}

		else
		{
			$template = array
			(
				'header',
				'menu',
				'contentPortfolio',
				'footer'
			);
		}
	}

	else if ($uri === '/about')
	{
		$title = 'About';

		if(isAjax())
		{
			$template = array
			(
				'contentAbout'
			);
		}

		else
		{
			$template = array
			(
				'header',
				'menu',
				'contentAbout',
				'footer'
			);
		}
	}

	else if ($uri === '/contact')
	{
		$title = 'Contact';

		if(isAjax())
		{
			$template = array
			(
				'contentContact'
			);
		}

		else
		{
			$template = array
			(
				'header',
				'menu',
				'contentContact',
				'footer'
			);
		}
	}

	else if ($uri === '/api/')
	{
		if(isAjax()) echo json_encode(['title' => 'Home']);
	}

	else if ($uri === '/api/blog')
	{
		if(isAjax()) echo json_encode(['title' => 'Blog']);
	}

	else if ($uri === '/api/portfolio')
	{
		if(isAjax()) echo json_encode(['title' => 'Portfolio']);
	}

	else if ($uri === '/api/about')
	{
		if(isAjax()) echo json_encode(['title' => 'About']);
	}

	else if ($uri === '/api/contact')
	{
		if(isAjax()) echo json_encode(['title' => 'Contact']);
	}

	else
	{
		header("HTTP/1.0 404 Not Found");
		require_once 'app/views/error/page404.php';
		exit;
	}	

	require_once 'app/views/index.php';


<?php

	if(is_array($template))
	{
		for($t = 0; $t < count($template); $t++)
		{
			include_once 'ui/' . $template[$t] . '.php';
		}
	}
  • Вопрос задан
  • 47 просмотров
Пригласить эксперта
Ответы на вопрос 1
@AUser0
Чем больше знаю, тем лучше понимаю, как мало знаю.
Ну так передавайте внутри HTML какой-нибудь тэг типа <div id='title-text' style='display:none;'>New Page Title</div>, а после вставления на страничку доставайте document.getElementById('title-text').innerText из него...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы