HTTP-GET-Anfrage in JavaScript?

Ich muss eine HTTP GET-Anfrage in JavaScript durchführen. Wie kann ich das am besten machen?

Ich muss dies in einem Mac OS X Dashcode Widget tun.

Hier ist Code, um es direkt mit JavaScript zu tun. Aber, wie bereits erwähnt, sind Sie viel besser dran mit einer JavaScript-Bibliothek. Mein Favorit ist jQuery.

Im folgenden Fall wird eine ASPX-Seite (die als REST-Dienst eines armen Mannes fungiert) aufgerufen, um ein JavaScript-JSON-Objekt zurückzugeben.

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;
        }                    
    }
}
Kommentare (2)

Prototyp macht es ganz einfach

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

Ajax

Am besten verwenden Sie eine Bibliothek wie Prototype oder jQuery.

Kommentare (0)