Eu preciso fazer uma solicitação HTTP GET em JavaScript. Qual'é a melhor maneira de fazer isso?
Preciso de fazer isto num Mac OS X dashcode widget.
Aqui está o código para fazer isso diretamente com JavaScript. Mas, como mencionado anteriormente, você ficaria muito melhor com uma biblioteca JavaScript. O meu favorito é jQuery.
No caso abaixo, uma página ASPX (que é a manutenção como serviço REST de um homem pobre) está sendo chamada para devolver um objeto JSON JavaScript.
var xmlHttp = null;
function GetCustomerInfo()
{
var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", Url, true );
xmlHttp.send( null );
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText == "Not found" )
{
document.getElementById( "TextBoxCustomerName" ).value = "Not found";
document.getElementById( "TextBoxCustomerAddress" ).value = "";
}
else
{
var info = eval ( "(" + xmlHttp.responseText + ")" );
// No parsing necessary with JSON!
document.getElementById( "TextBoxCustomerName" ).value = info.jsonData[ 0 ].cmname;
document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
}
}
}