¿Solicitud HTTP GET en JavaScript?

Necesito hacer una petición HTTP GET en JavaScript. ¿Cuál es la mejor manera de hacerlo?

Necesito hacer esto en un widget dashcode de Mac OS X.

Aquí está el código para hacerlo directamente con JavaScript. Pero, como se mencionó anteriormente, usted & #39; d ser mucho mejor con una biblioteca de JavaScript. Mi favorita es jQuery.

En el caso de abajo, una página ASPX (que está sirviendo como un pobre servicio REST) está siendo llamada para devolver un objeto JSON de 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;
        }                    
    }
}
Comentarios (2)

Prototipo lo hace muy sencillo

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});
Comentarios (2)

Ajax

Lo mejor es utilizar una biblioteca como Prototype o jQuery.

Comentarios (0)