<< Click to Display Table of Contents >> Exemplo simples |
![]() ![]() ![]() |
Intro
Atualizar informações da tela consultando um servidor (c#) sem fazer PostBack usando JavaScript puro.
É passado um parametro opcional para o c#.
O retorno é assincrono na função updatePage()
Tela
Client - criando request assincrono
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function createRequest() {
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 getDataHoraServidor() {
createRequest();
var parametros = document.getElementById('edSufixo').value;
// caminho para a pagina na web que retorna a data e hora local (não coloque www.caminho.com/a.aspx a menos que esteja rodando o test.html também na web)
var url = "a.aspx?p=" + parametros; // "http://teste.market.com.br/a.aspx";
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
div = document.getElementById("div_datahora");
div.innerHTML = request.responseText;
}
}
}
</script>
</head>
<body>
<form>
Sufixo (opcional):<input id="edSufixo" value="" />
<p>
<input value="Mostrar a data e hora" type="button" onclick="getDataHoraServidor();" />
</p>
<div id="div_datahora">
<p>Aqui vai mostrar data e hora</p>
</div>
</form>
</body>
</html>
Server
using System;
public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1; // Requerido para manter a pagina no cache do navegador
Response.ContentType = "text/plain";
if (Request.QueryString["p"] != null)
Response.Write(Request.QueryString["p"].ToString());
Response.Write(DateTime.Now.ToString());
Response.End();
}
}